您的位置:首页 > 编程语言 > Python开发

Python3.4中filter函数,map函数和reduce函数

2016-04-15 14:23 645 查看
filter函数:

filter()为已知的序列的每个元素调用给定的布尔函数,调用中,返回值为非零的元素将被添加至一个列表中

[python] view
plain copy

 





>>> def f1(x):  

if x > 20:  

return True  

else:  

return False  

  

>>> l1 = [ 1, 2, 3, 42, 67, 16 ]  

>>> filter( f1, l1)  

<filter object at 0x01F594F0>  

>>> l2 = filter( f1, l1 )  

>>> print(l2)  

<filter object at 0x01FA30D0>  

>>> l2.__next__  

<method-wrapper '__next__' of filter object at 0x01FA30D0>  

>>> l2.__next__()  

42  

>>> l2.__next__()  

67  

>>> l2.__next__()  

Traceback (most recent call last):  

  File "<pyshell#14>", line 1, in <module>  

    l2.__next__()  

StopIteration  

map函数:
map()将函数调用映射到每个序列的对应元素上并返回一个含有所有返回值的列表

[python] view
plain copy

 





>>> def f1( x, y ):  

return (x,y)  

  

>>> l1 = [ 0, 1, 2, 3, 4, 5, 6 ]  

>>> l2 = [ 'Sun', 'M', 'T', 'W', 'T', 'F', 'S' ]   

>>> l3 = map( f1, l1, l2 )  

>>> print(list(l3))  

[(0, 'Sun'), (1, 'M'), (2, 'T'), (3, 'W'), (4, 'T'), (5, 'F'), (6, 'S')]  

  

>>> print( list(map(f2, l1) ))  

[0, 2, 4, 6, 8, 10, 12]  

  

>>> print( list(map(f2, l2) ) )  

['SunSun', 'MM', 'TT', 'WW', 'TT', 'FF', 'SS']  

  

>>> def f3( x, y ):  

return x*2, y*2  

  

>>> print( list(map(f3, l1, l2) ))  

[(0, 'SunSun'), (2, 'MM'), (4, 'TT'), (6, 'WW'), (8, 'TT'), (10, 'FF'), (12, 'SS')]  

reduce函数:
在Python 3里,reduce()函数已经被从全局名字空间里移除了,它现在被放置在fucntools模块里 用的话要 先引
入:
>>> from functools import reduce
>>> print(l1)
[0, 1, 2, 3, 4, 5, 6]
>>> reduce( f4, l1 )
21
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: