gpt4 book ai didi

python - "Float"在 python2 中应用 reduce + sum 时对象不可迭代

转载 作者:太空狗 更新时间:2023-10-30 02:44:04 25 4
gpt4 key购买 nike

我想将 reduce(sum, iterable) 应用于 float 列表flist = [0.2, 0.06, 0.1, 0.05, 0.04, 0.3]

print list(reduce(sum, flist)) 返回TypeError: 'float' 对象不可迭代

为什么,当 flist 是一个可迭代对象时?

最佳答案

实际问题出在 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

因此,您不能在此处使用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

注意:在使用reduce 之前,您可能需要阅读 BDFL's take on its use .此外,reduce 已移至 Python 3.x 中的 functools 模块。

关于python - "Float"在 python2 中应用 reduce + sum 时对象不可迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31070006/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com