"Float" object is not iterable when applying reduce + sum in python2

时间:2015-06-26 09:47:47

标签: python list python-2.7 reduce

I want to apply reduce(sum, iterable) to a list of float numbers flist = [0.2, 0.06, 0.1, 0.05, 0.04, 0.3].

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

Why, when flist IS an iterable?

2 个答案:

答案 0 :(得分:4)

The actual problem is with the sum function. It accepts only an iterable, not two individual values. For example,

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

So, you cannot use sum here, instead you can use a custom lambda function or operator.add, like this

>>> from operator import add
>>> reduce(add, flist, 0.0)
0.75
>>> reduce(lambda a, b: a + b, flist, 0.0)
0.75

Note: Before using reduce, you might want to read the BDFL's take on its use. Moreover, reduce has been moved to functools module in Python 3.x.

答案 1 :(得分:1)

You can use reduce as follows which will sum up all elements in flist:

reduce(lambda x,y: x+y,flist)

which gives you 0.75.

In this particular case you do not need reduce but could also just use

sum(flist)