python的map与reduce与filter

map(f, Itera)  # 对每一个元素都使用f(x)

>>> sq = lambda x:x**2
>>> l = map(sq,[-1,0,1,2,-3])
>>> list(l)
[1, 0, 1, 4, 9]

当然也可以传入两个参数的:

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

reduce(f, Itera)   # 对前一个x1,x2把结果f(x1,x2)继续和序列的下一个元素x3做累积计算f(f(x1,x2),x3)

函数f必须有两个参数x,y

>>> from functools import reduce
>>> def add(x,y): #定义一个相加函数
        return x+y

>>> reduce(add,[1,2,3,4,6])
16

add(x,y)是我们定义的一个函数,将add函数和[1,2,3,4,6]列表传入reduce函数,就相当于1+2+3+4+6 =16。即把结果继续和序列的下一个元素做累加。

即reduce的作用是:把结果继续和序列的下一个元素做累积计算。

filter(f, Itera)  # 根据判断结果自动过滤掉不符合条件的元素,返回由符合条件元素组成的iterator

>>> is_odd = lambda x:x%2==1
>>> list(filter(is_odd, [1, 4, 6, 7, 9, 12, 17]))
[1, 7, 9, 17]

另外,map对象只能保持一次:被使用一次后其内容被清除

>>> numbers = 2,4,8.1
>>> numbers = map(lambda x:isinstance(x,(int,)),numbers)
>>> reduce(lambda x,y: x and y, numbers) # 使用numbers
False
>>> numbers 
<map object at 0x000002A9753F7C50>
>>> list(numbers) # 内容被清除了
[]


>>> numbers = 2,4,8.1
>>> numbers = map(lambda x:isinstance(x,(int,)),numbers)
>>> list(numbers) # 使用numbers
[True, True, False]
>>> list(numbers) # 内容被清除了
[]

# 最好以列表保存
>>> numbers = 2,4,8.1
>>> numbers = list(map(lambda x:isinstance(x,(int,)),numbers))
>>> numbers
[True, True, False]
>>> reduce(lambda x,y: x and y, numbers)
False
# 当然元组以保存也行
>>> numbers = 2,4,8.1
>>> numbers = tuple(map(lambda x:isinstance(x,(int,)),numbers))
>>> numbers
(True, True, False)
>>> reduce(lambda x,y: x and y, numbers)
False
原文地址:https://www.cnblogs.com/cymwill/p/8366340.html