1.filter
filter(function,sequence)
对sequence中的item依次执行function(item),将执行的结果为True(符合函数判断)的item组成一个list、string、tuple(根据sequence类型决定)返回。
#!/usr/bin/env python
# encoding: utf-8
"""
@author: 侠之大者kamil
@file: filter.py
@time: 2016/4/9 22:03
"""
#filter map reduce lambda
def f1(x):
return x % 2 != 0 and x % 3 != 0
a = filter(f1, range(2,25))
print(a)#<filter object at 0x7f7ee44823c8>
#这种情况是因为在3.3里面,filter()的返回值已经不再是list,而是iterators.
print(list(a))
def f2(x):
return x != "a"
print(list(filter(f2,"dfsafdrea")))
结果:
ssh://kamil@192.168.16.128:22/usr/bin/python3 -u /home/kamil/py22/jiqiao0406/fmrl.py
<filter object at 0x7f4d1ca5e470>
[5, 7, 11, 13, 17, 19, 23]
['d', 'f', 's', 'f', 'd', 'r', 'e'] Process finished with exit code 0
2.map
语法与filter类似
#!/usr/bin/env python
# encoding: utf-8
"""
@author: 侠之大者kamil
@file: map.py
@time: 2016/4/9 22:22
"""
def cube(x):
return x * x *x
a = map(cube,range(10))
print(list(a))
def add(x,y,z):
return x + y +z
b = map(add,range(5),range(5),range(5))
print(list(b))
结果:
ssh://kamil@192.168.16.128:22/usr/bin/python3 -u /home/kamil/py22/jiqiao0406/map.py
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
[0, 3, 6, 9, 12] Process finished with exit code 0
3.reduce
reduce已经取消了,如想使用,可以用fuctools.reduce来调用。但是要先导入fuctools, 即输入:import fuctools
4.lambda
快速定义最小单行函数
g = lambda x:x *2
print(g(5))
print((lambda x:x *2)(5))
结果:
10
10