使用 reduce 函数时出现意外的 TypeError

Unexpected TypeError when using reduce function

这是代码行:

product = list(reduce(lambda a, b: a*b, [2,2,2,2,2]))

错误:

TypeError: 'int' object is not iterable

>>> reduce(lambda a, b: a*b, [2,2,2,2,2])
32

所以你不能list

如果你想把你的结果放在一个列表中,你可以使用这个代码:

import functools
product = [functools.reduce((lambda x,y:x*y),[2,2,2,2,2])]
print(product)

列表函数无法使用,因为它对应于一个类型转换,而您的结果是一个整数,这是不可能的。