【发布时间】: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