문제

I'm using Python 3.2. Tried this:

xor = lambda x,y: (x+y)%2
l = reduce(xor, [1,2,3,4])

And got the following error:

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

Tried printing reduce into interactive console - got this error:

NameError: name 'reduce' is not defined


Is reduce really removed in Python 3.2? If that's the case, what's the alternative?

도움이 되었습니까?

해결책

It was moved to functools.

다른 팁

You can add

from functools import reduce

before you use the reduce.

Or if you use the six library

from six.moves import reduce

In this case I believe that the following is equivalent:

l = sum([1,2,3,4]) % 2

The only problem with this is that it creates big numbers, but maybe that is better than repeated modulo operations?

you need to install and import reduce from functools python package

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top