在python2中应用reduce + sum时“Float”对象不可迭代

min*_*als 4 python reduce list python-2.7

我想申请reduce(sum, iterable)浮点数列表 flist = [0.2, 0.06, 0.1, 0.05, 0.04, 0.3]

print list(reduce(sum, flist)) 返回 TypeError: 'float' object is not iterable

为什么,什么时候flist是可迭代的?

the*_*eye 5

实际问题出在sum函数上。它只接受一个可迭代的,而不是两个单独的值。例如,

>>> sum(1, 2)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> sum([1, 2])
3
Run Code Online (Sandbox Code Playgroud)

因此,您不能sum在这里使用,而是可以使用自定义 lambda 函数或operator.add,像这样

>>> from operator import add
>>> reduce(add, flist, 0.0)
0.75
>>> reduce(lambda a, b: a + b, flist, 0.0)
0.75
Run Code Online (Sandbox Code Playgroud)

注意:在使用之前reduce,您可能需要阅读BDFL 对其使用的看法。此外,reduce已移至functoolsPython 3.x 中的模块。