python新手,以前写nodejs,java的选手java
python的lambda有点相似nodejs中的arrow function,可是格式可能比较麻烦node
lambda x: x*2 #即一个返回x平方的函数 [ x if x > 3 else -1 for x in range(5) ] #在0到4中选出大于3的数字,若是没有在缺失位置返回-1 结果[-1,-1,-1,4] [ x for x in range(5) if x > 3] # 在0到4中返回大于3的数字 结果[4] 这两个看似很像等其实不一样。 这种很方便的数组还能够多重 [ x* y for x in range(4) for y in range(4)] 运行的方式,就是先x的大循环,而后y是它的子循环 结果[0, 1, 2, 3, 1, 2, 3, 4, 2, 3, 4, 5, 3, 4, 5, 6]
下面就是关于python类型识别的问题python
对于普通的类型而言,常见的python类型又int,float,str,None,list,dict,datetime之类的,可是咱们如何处理一个由字符串构成的数据的类型呢?数组
name = [None,'123,333',123.33,'444.44','678','{"123456","567"}'] #一个由各类类型数据混合而成的数组,咱们目标是统计各类类型的数据的次数 #先来一个检验类型的函数 def jtype(data): ''' 识别数据的类型 @data 数组数据 ''' if type(data) == str: if data == '': types[type(None)] += 1 return type(None) elif data.startswith('{'): return type([]) else: try: int(data) return type(1) except ValueError as e: try: float(data) return type(1.1) except ValueError as e: return type('') return types else: return type(data)
首先经过type ==str 咱们能够判断当前的类型是不是咱们须要转换的字符串类型,若是是,进行咱们的类型判断,先进行的None空类型的判断,顺序挺重要,先进行空判断再进行其余步骤不然如下的问题都会出异常就没意义了。其次进行的是数组的判断,这边就不写字典了,方法差很少,这边定义以'{'开头的的数据为数组。若是是咱们再进行其余的判断。到了数字类型的话要先进行int的判断,再到float,都不行就是str了。函数
def count_type(data_set): from collections import defaultdict types = defaultdict(int) for dp in data_set: types[jtype(dp)] += 1 return types #得出结果 defaultdict(<type 'int'>, {<type 'list'>: 1, <type 'float'>: 2, <type 'str'>: 1, <type 'NoneType'>: 1, <type 'type'>: 1}) if type(int) == int: print 'same' elif type(1) == int: print 'same 2' else: print 'no both'
结果辉县市same 2,由于int自己是type类型,type(int)结果仍是typecode