filter()为已知的序列的每个元素调用给定的布尔函数,调用中,返回值为非零的元素将被添加至一个列表中
- >>> 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()将函数调用映射到每个序列的对应元素上并返回一个含有所有返回值的列表
- >>> 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