使用reduce函数时触发TypeError: 'int'对象不可迭代报错
报错原因
reduce对传入的可迭代对象做累积运算后,返回值是单个聚合结果,不是可迭代对象。
你的代码中reduce(lambda a, b: a*b, [2,2,2,2,2])会依次执行元素相乘,最终返回整数32。外层调用list()时要求传入可迭代对象,但整数不支持迭代,因此抛出TypeError: 'int' object is not iterable。
注意:Python 3 中reduce已从内置函数移到functools模块,使用前需要先导入,否则会先触发NameError。
修复方案
根据实际需求选择对应写法:
- 如果仅需要最终的乘积结果(单个整数),直接去掉外层的
list()包装即可:
from functools import reduce product = reduce(lambda a, b: a*b, [2,2,2,2,2]) # 输出结果:32
- 如果需要得到累积计算每一步的结果组成的列表(即
[2, 4, 8, 16, 32]),reduce本身不返回中间过程值,可以换成itertools.accumulate实现:
from itertools import accumulate product_list = list(accumulate([2,2,2,2,2], lambda a, b: a*b)) # 输出结果:[2, 4, 8, 16, 32]
内容的提问来源于stack exchange,提问作者Fabian Rizo
相关产品推荐
相关产品推荐

