python - "Float" object is not iterable when applying reduce + sum in python2 -
i want apply reduce(sum, iterable) 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 not iterable
why, when flist iterable?
the actual problem sum function. accepts iterable, not 2 individual values. example,
>>> sum(1, 2) traceback (most recent call last): file "<input>", line 1, in <module> typeerror: 'int' object not iterable >>> sum([1, 2]) 3 so, cannot use sum here, instead can use custom lambda function or operator.add, this
>>> operator import add >>> reduce(add, flist, 0.0) 0.75 >>> reduce(lambda a, b: + b, flist, 0.0) 0.75 note: before using reduce, might want read bdfl's take on use. moreover, reduce has been moved functools module in python 3.x.
Comments
Post a Comment