本文共 1213 字,大约阅读时间需要 4 分钟。
以下代码均采用Python 3.5.2编写。新建一个名为HelloWorld.py的文件,当然名字无所谓,输入以下代码:
#filterdef larger100(a): return a>100for i in filter(larger100,[10,56,101,500]): print(i)#reducefrom functools import reducedata_list = [1,2,5,7,9]result=reduce(lambda x,y: x+y, data_list)print(result)#Generator Expressiondef gen(): for i in range(4): yield ifor i in gen(): print(i)gen = (x for x in range(4))for i in gen: print(i)#List Comprehensionl=[]for i in range(5): l.append(i**2)print(l)l=[x**2 for x in range(5)]print(l)x1=[1,3,5]y1=[9,12,13]l=[x**2 for (x,y) in zip(x1,y1) if y>10]print(l)#Lazy Evaluationa=range(10)result=map(lambda x:x**2, a)for i in result: print(i)#itertoolsfrom itertools import *#count(5,2) 5,7,9,11,13,...#cycle("abc") a b c a b c a b ...#repeat(1.2) 1.2 1.2 1.2 ...for i in repeat(10,5): print(i)for i in chain([1,2,3],[4,5,7]): print(i)def height_class(h): if h>180: return "tall" elif h<160: return "short" else: return "middle"friends = [191, 158, 159, 165, 170, 177, 181, 182, 190]friends=sorted(friends, key=height_class)print(friends)for m,n in groupby(friends, key=height_class): print(m) print(list(n))
方便起见,可将未读到的代码注释掉,一段段阅读运行,查看结果,理解原理。
转载地址:http://ryhtx.baihongyu.com/