【Python】 map,filter,reduce的区别

map

# Make an iterator that computes the function using arguments from
    #each of the iterables.  Stops when the shortest iterable is exhausteds
def square(x) :            # 计算平方数
  return x ** 2
map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
#[1, 4, 9, 16, 25]
map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
#[1, 4, 9, 16, 25]
 
# 提供了两个列表,对相同位置的列表数据进行相加
map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
#[3, 7, 11, 15, 19]

filter

# Return an iterator yielding those items of iterable for which function(item)
    # is true. If function is None, return the items that are true
def is_odd(n):
    return n % 2 == 1
# 筛选出奇数 
newlist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(newlist)
# [1, 3, 5, 7, 9]

reduce

# 用传给 reduce 中的函数 function(有两个参数)先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果
from functools import reduce

def add(x, y) :            # 两数相加
    return x + y
sum1 = reduce(add, [1,2,3,4,5])   # 计算列表和:1+2+3+4+5
sum2 = reduce(lambda x, y: x+y, [1,2,3,4,5])  # 使用 lambda 匿名函数
print(sum1)
print(sum2)

# 15
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容