filter(function,sequence):对sequence中的item依次执行function(item),将执行结果为True的item组成一个List/string/Tuple(取决与sequence的类型)返回:
-
In [84]: def f(x):
-
....: return x % 2 !=0
-
....:
-
-
In [85]: filter(f,range(1,11))
-
Out[85]: [1, 3, 5, 7, 9]
map(function,sequence):对sequence中的item一次执行function(item),见执行结果组成一个list返回:
-
In [86]: def f2(x):
-
....: return x ** 2
-
....:
-
-
In [87]: map(f2,range(1,11))
-
Out[87]: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
reduce(function,sequence,starting_value):对sequence中的item顺序迭代调用function,如果有starting_value,还可以作为初始值调用,例如可以用来对list求和:
-
In [88]: def add(x,y):
-
....: return x + y
-
....:
-
-
In [89]: reduce(add,range(1,11))
-
Out[89]: 55
-
-
In [90]: reduce(add,range(1,11),20)
-
Out[90]: 75
lambda:可以定义单行的最小函数,也叫匿名函数
-
In [91]: a = lambda x: x**2
-
-
In [92]: a(5)
-
Out[92]: 25
-
-
In [93]: (lambda x: x**2)(5)
-
Out[93]: 25
阅读(1469) | 评论(0) | 转发(0) |