python 内建函数 filter() 过滤函数
seq[0] seq[1] seq[3] ''' seq[n-1]
seq [ | | | | ]
↓ ↓ ↓ ↓
|----------------------------------------|
| 0 1 1 bool_func |
|----------------------------------------|
↓ ↓
filter_seq[ seq[1] sed[3] ]
filter()
例子一:
- >>> from random import randint
- >>> allnum = []
- >>> def filter_seq(n):
- ... return n % 2
- ...
- >>> for i in range(9):
- ... allnum.append(randint(1,100))
- ...
- >>> allnum
- [59, 7, 35, 69, 57, 15, 98, 73, 43]
- >>> print filter(filter_seq,allnum)
- [59, 7, 35, 69, 57, 15, 73, 43]
6 -7 的目的是产生 10个随机数,然后调用filter来益处所有的偶数
重构代码,使用lambda 代替filter_seq():
- >>> from random import randint
- >>> allnum = []
- >>> for i in range(9):
- ... allnum.append(randint(1,100))
- ...
- >>> allnum
- [75, 15, 98, 98, 64, 71, 55, 27, 70]
- >>> print filter(lambda x:x%2,allnum)
- [75, 15, 71, 55, 27]
也可以使用列表进行遍历
- >>> from random import randint
- >>> allnum = []
- >>> for i in range(9):
- ... allnum.append(randint(1,100))
- ...
- >>> print ([n for n in allnum if n%2])
- [37, 9, 11, 43, 45, 59]
使代码更简洁
- >>> from random import randint
- >>> print [n for n in [randint(1,100) for i in range(9)] if n % 2]
- [93, 25, 25, 89, 11, 61]
map()
map() 函数与filter()很相似,因为他们都是可以处理序列的,map()作用是调用映射,并返回所有值的列表
- >>> allnum
- [37, 9, 11, 48, 88, 43, 45, 64, 59]
- >>> map(lambda x:x+2,allnum)
- [39, 11, 13, 50, 90, 45, 47, 66, 61]
allnum是一个list,利用map 对每个列表的值+2,并且将这个汗水和一个数字的列表返回给map(),这个列表是和原始结果的数字集合.
- >>> map(lambda x:x*x*x,range(4))
- [0, 1, 8, 27]
- >>> map(lambda x:x+x,'abcdefg')
- ['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg']
map()函数也支持多个seq.例如:
- >>> def add(x,y):
- ... return x + y
- ...
- >>> map(add,range(10),range(10))
- [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
reduce()函数使用了一个二元函数,( 函数可以按照给定的方法把输入参数中上序列缩减为单个的值,具体的做法如下:首先从序列中去除头两个元素并把它传递到那个二元函数中去,求出一个值,再把这个加到序列中循环求下一个值,直到最后一个值 )
- >>> reduce(lambda x,y:x+y,range(1,4))
- 6
- For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5)
本文出自 “奋斗的小子” 博客,请务必保留此出处http://crazyming.blog.51cto.com/1048571/975442