filter&map
1.filter函数
filter()函数用于过滤序列,过滤掉不符合条件的元素,Python3以后返回一个迭代器对象(可以用list()转化为列表查看)。
filter()函数接受两个参数,第一个为函数或者None,第二个为序列。
如果第一个参数是函数,则把序列里的每一个元素传到函数里进行判断,返回True的元素被放到新的列表中。
如果第一个参数是None,则返回序列中为True的元素。
def odd(x):
return x % 2
tmp = range(10)
show = filter(odd, tmp)
show1=filter(None,tmp)
print(show)#返回迭代器对象
print(list(show))#返回True,即是奇数的数
print(list(show1))#返回True,即非零数
输出:
<filter object at 0x000001FB6E020128>
[1, 3, 5, 7, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
2.map函数
map()函数根据提供函数对指定序列做映射。
map()函数接受两个参数,第一个为函数,第二个可以为一个或者多个序列,同filter一样返回一个迭代器对象。
注意:若有多个序列,每个序列元素数量不同,则会按照有最少元素的进行。
def square(x):
return x * x
def add(x, y):
return x + y
print(map(square, range(5)))
print(list(map(square, range(5))))
print(list(map(add, [1, 2, 3], [1, 2, 3])))
print(list(map(add, [1, 2, 3], [1, 2])))
输出:
<map object at 0x00000200466B02E8>
[0, 1, 4, 9, 16]
[2, 4, 6]
[2, 4]