【问题标题】:Reduce() after filter() in Python?在Python中的filter()之后减少()?
【发布时间】:2018-03-09 20:05:42
【问题描述】:

我对 python 中的两个函数有疑问:reduce() 和 filter()。 可以在filter()之后使用reduce()吗?

我在 sklearn 中使用了波士顿数据集。

x = load_boston()
x_target = x.target
xx = filter(lambda x: x > 20, x_target)

而且它运行良好。 接下来我想使用 reduce() 函数来总结 xx 中的值。

from functools import reduce
xxx = reduce(lambda x,y: x+y, xx)

我收到错误:

TypeError                                 Traceback (most recent call last)
<ipython-input-64-062fcc861672> in <module>()
      1 from functools import reduce
----> 2 xxx = reduce(lambda x,y: x+y, xx)

TypeError: reduce() of empty sequence with no initial value

有什么建议吗?

【问题讨论】:

  • filter() 生成一个迭代器,您可以在 reduce() 中使用它就好了。但是您的错误表明您已经使用了过滤器中的所有值。过滤器不可重复使用,您需要重新创建它。

标签: python apache-spark filter bigdata reduce


【解决方案1】:

这意味着过滤器函数在您的列表上返回一个空列表。这里有一个例子:

sample = [2,3,4,5,6,7,8]
filter(lambda x: x%2 == 0, sample)
>>> [2, 4, 6, 8]
reduce(lambda x,y: x+y, filter(lambda x: x%2 == 0, sample))
>>> 20

所以,您的代码应该可以工作。

这是python 2.7。在 python 3+ 中应该不同

编辑:使用python3

 from functools import reduce
 sample = [2,3,4,5,6,7,8]
 f = filter(lambda x: x%2 == 0, sample)
 reduce(lambda x,y: x+y, f)
 >>> 20

以同样的方式工作; )

【讨论】:

  • 是的,它在 Python 3 中有所不同,这就是 OP 问题的根源。
【解决方案2】:

是的,你可以在reduce() 中使用filter() 对象就好了:

>>> from functools import reduce
>>> values = range(10, 30)
>>> filtered = filter(lambda x: x > 20, values)
>>> reduce(lambda x, y: x + y, filtered)
225

然而,filter() 对象是一个迭代器;它将根据需要产生过滤值,并且当它到达末尾时不会产生其他任何东西。所以你需要确保在传递给reduce()之前不要清空它:

>>> filtered = filter(lambda x: x > 20, values)
>>> filtered
<filter object at 0x10ee64ac8>
>>> list(filtered)
[21, 22, 23, 24, 25, 26, 27, 28, 29]
>>> reduce(lambda x, y: x + y, filtered)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: reduce() of empty sequence with no initial value

当您需要在多个地方重复使用 filter() 对象时,重新创建它。

【讨论】:

  • 错误是否发生在 Python 3 中?因为在 2.7 filter 返回一个列表,它是否更改为 filter object
  • @Vinny:是的,Python 3 filter() 不返回列表,过滤是按需进行的。
猜你喜欢
  • 2019-08-24
  • 1970-01-01
  • 2020-08-24
  • 2015-07-08
  • 1970-01-01
  • 2016-02-16
  • 1970-01-01
  • 1970-01-01
  • 2012-07-16
相关资源
最近更新 更多