我对python中的两个函数有疑问:减()和filter()。我们可以在过滤器()之后使用减()吗?
我在滑雪板上使用波士顿数据集。
x = load_boston()
x_target = x.target
xx = filter(lambda x: x > 20, x_target)而且效果很好。接下来,我希望使用减()函数来总结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有什么建议吗?
发布于 2017-09-28 07:17:16
是的,您可以在filter()中很好地使用reduce()对象:
>>> 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()对象时,重新创建它。
发布于 2017-09-28 07:14:31
这意味着filter函数在列表上返回一个空列表。这里有一个例子:
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所以,你的代码应该能工作。
这是python2.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(工作方式相同;)
https://stackoverflow.com/questions/46463046
复制相似问题