美文网首页
reduce、map、filter

reduce、map、filter

作者: butters001 | 来源:发表于2021-02-22 18:13 被阅读0次
functools.reduce(function, iterable[, initializer])

将两个参数的 function[1] 从左至右积累地应用到 iterable 的条目,以便将该可迭代对象缩减为单一的值 [2]。 例如,reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 是计算 ((((1+2)+3)+4)+5) 的值。 左边的参数 x 是积累值而右边的参数 y 则是来自 iterable 的更新值。 如果存在可选项 initializer,它会被放在参与计算的可迭代对象的条目之前,并在可迭代对象为空时作为默认值。 如果没有给出 initializer 并且 iterable 仅包含一个条目,则将返回第一项。

解释:

[1]function 需要接收两个参数;

[2]:可迭代对象最终会缩减为单一的值。

In [279]: reduce(lambda x, y: x + y, [1,2,3,4,5])
Out[279]: 15
map(function, iterable, ...)

对iterable里的每一个或一组数据,执行function方法,并将结果放置到新的列表。

Python 2.x 返回列表。

Python 3.x 返回迭代器。

In [280]: def square(x):
     ...:     return x ** 2
     ...: 

In [281]: map(square, [1,2,3,4,5])
Out[281]: <map at 0x10b855040>

In [282]: list(map(square, [1,2,3,4,5]))
Out[282]: [1, 4, 9, 16, 25]
In [283]: list(map(lambda x: x ** 2, [1, 2, 3, 4, 5]))
Out[283]: [1, 4, 9, 16, 25]
# 提供了两个列表,对相同位置的列表数据进行相加
In [285]: list(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
Out[285]: [3, 7, 11, 15, 19]
filter(function, iterable)

过滤序列,过滤掉不符合条件的元素,返回由符合条件元素组成的新列表。

Python 2.x 返回列表。

Python 3.x 返回迭代器。

过滤出列表中的所有奇数:

In [286]: def is_odd(n):
     ...:     return n % 2 == 1
     ...: 

In [287]: filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Out[287]: <filter at 0x10baac370>

In [288]: list(filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]))
Out[288]: [1, 3, 5, 7, 9]
结论
  • reduceiterable的数据进行累计,返回单一的结果
  • mapiterable的每一个元素都执行function,返回的列表(迭代器)的长度 和 参数(iterable)的长度一致
  • filter 根据function进行过滤,保留满足条件的元素(function()返回True)

相关文章

网友评论

      本文标题:reduce、map、filter

      本文链接:https://www.haomeiwen.com/subject/yxyxfltx.html