NameError: Python中未定义'name 'reduce
我在用Python 3.2,试了这个:
xor = lambda x,y: (x+y)%2
l = reduce(xor, [1,2,3,4])
结果出现了以下错误:
l = reduce(xor, [1,2,3,4])
NameError: name 'reduce' is not defined
我还在交互式控制台里打印了reduce
,结果也出现了这个错误:
NameError: name 'reduce' is not defined
请问reduce
在Python 3.2里真的被去掉了吗?如果真是这样,那有什么替代的方法呢?
7 个回答
10
或者如果你使用six库的话
from six.moves import reduce
275
你可以在使用 reduce 之前添加
from functools import reduce
。
346
它被移到了 functools
这个地方。