Python学习之路(9)——内置函数filter和map

内置函数filter

过滤器:filter。filter接收两个参数,第一个参数是函数或者None,第二个参数是可迭代的数据。

filter将第二个参数的可迭代的数据中的每一个元素都放入第一个参数中进行计算,并返回值为True的值。

返回的是一个filter对象。

1)如果第一个参数是函数,则相当于生成器推导式(item for item in iterable if function(item))

2)如果第二个参数是None,则相当于生成器推导式(item for item in iterable if item)

>>> filter(None, [1, 0, False, True])
<filter object at 0x0000000003389128>
>>> list(filter(None, [1, 0, False, True]))
[1, True]

但是最常用的还是使用filter通过函数进行过滤:

>>> def odd(x):
	return x % 2

>>> temp = range(10)
>>> show = filter(odd, temp)
>>> list(show)
[1, 3, 5, 7, 9]

使用lambda表达式:

>>> list(filter(lambda x : x % 2, range(10)))
[1, 3, 5, 7, 9]

  

内置函数map

映射:map。参数与filter一样,其作用是,将iterable中的每一个元素作为函数的参数进行加工运算,直到所有元素都运算完毕后返回一个新的序列。

返回值是map对象。

>>> list(map(lambda x : x * 2, range(10)))
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

多参数的map方法:

>>> list(map(lambda x, y : [x, y, x+y], [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
[[1, 2, 3], [3, 4, 7], [5, 6, 11], [7, 8, 15], [9, 10, 19]]

  

 

  

posted on 2018-02-27 11:58  nicolas_Z  阅读(149)  评论(0)    收藏  举报

导航