map + filter + reduce

map
  是对 集合 里面的元素一个接一个的进行某种运算,常常与lambda 结合使用
 
#求平方
items = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, items))
 
此外,map还可以对函数进行迭代运算:
#-----------------
def multiply(x):
    return (x*x)
 
def add(x):
    return (x+x)
   
  funcs = [multiply, add]
 
for i in range(5):
  value = list(map(lambda x: x(i), funcs))
print(value)
#-----------------
定义了两个函数,作为对象组成集合,后面加括号代表传参调用,输出结果如下
# [0, 0]
# [1, 2]
# [4, 4]
# [9, 6]
# [16, 8]
 
filter
  是对 集合 里面的元素一个接一个的判断,返回结果是True的元素,类似于for,但是内建函数更快速
number_list = range(-5, 5)
less_than_zero = list(filter(lambda x: x < 0, number_list))
print(less_than_zero)
 
# Output: [-5, -4, -3, -2, -1]
 
 
reduce
  是对 集合 里面的每相邻两个元素进行滚动计算
 
from functools import reduce
 
product = reduce((lambda x, y: x * y), [1, 2, 3, 4])
 
# 计算过程是1*2,结果*3,结果*4 
Output: 24
原文地址:https://www.cnblogs.com/springbrotherhpu/p/8227989.html