NameError:名称'reduce'未在Python中定义

Ser*_*gey 176 python reduce python-3.2

我正在使用Python 3.2.试过这个:

xor = lambda x,y: (x+y)%2
l = reduce(xor, [1,2,3,4])
Run Code Online (Sandbox Code Playgroud)

并得到以下错误:

l = reduce(xor, [1,2,3,4])
NameError: name 'reduce' is not defined
Run Code Online (Sandbox Code Playgroud)

尝试打印reduce到交互式控制台 - 出现此错误:

NameError: name 'reduce' is not defined
Run Code Online (Sandbox Code Playgroud)


reduce在Python 3.2真的删除?如果是这样的话,还有什么选择呢?

Ign*_*ams 265

它被转移到了functools.

  • @ julio.alegria:因为[Guido讨厌它](http://www.artima.com/weblogs/viewpost.jsp?thread=98196). (44认同)
  • @ IgnacioVazquez-Abrams中引用的文章对于如何以更易读的方式编写大多数案例提出了一些非常好的观点.对我来说,这是通过在list_of_dicts中为`item(item ['key']编写)来实现的. (6认同)
  • 这应该是核心语言中的 (2认同)

小智 170

你可以加

from functools import reduce
Run Code Online (Sandbox Code Playgroud)

在使用reduce之前.

  • 先前的用户已经回答了该问题,并且答案与他的回答相同 (3认同)

Azd*_*325 10

或者如果你使用六库

from six.moves import reduce
Run Code Online (Sandbox Code Playgroud)