map, reduce和filter(函数式编程)

# map可以用于对可遍历结构的每个元素执行同样的操作,批量操作:
map(lambda x: x**2, [1, 2, 3, 4])                 # [1, 4, 9, 16]
map(lambda x, y: x + y, [1, 2, 3], [5, 6, 7])     # [6, 8, 10]
  
# 在Python3种输出上述结果
result1=list(map(lambda x: x**2, [1, 2, 3, 4]) )                # [1, 4, 9, 16]
print(result1)
result2(map(lambda x, y: x + y, [1, 2, 3], [5, 6, 7]))     # [6, 8, 10]
print(result2)

# reduce则是对可遍历结构的元素按顺序进行两个输入参数的操作
# 并且每次的结果保存作为下次操作的第一个输入参数,还没有遍历的元素作为第二个输入参数
# 这样的结果就是把一串可遍历的值,减少(reduce)成一个对象
from functools import reduce
res=reduce(lambda x, y: x + y, [1, 2, 3, 4])    # ((1+2)+3)+4=10
print(res)

# filter顾名思义,根据条件对可遍历结构进行筛选
filter(lambda x: x % 2, [1, 2, 3, 4, 5])    # 筛选奇数,[1, 3, 5]

  

猜你喜欢

转载自www.cnblogs.com/lcxiao/p/11361001.html