NameError: name 'reduce' is not defined in Python

前端 未结 5 721
萌比男神i
萌比男神i 2020-11-29 17:49

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 = re         


        
相关标签:
5条回答
  • 2020-11-29 18:03

    It was moved to functools.

    0 讨论(0)
  • 2020-11-29 18:04

    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?

    0 讨论(0)
  • 2020-11-29 18:15

    You can add

    from functools import reduce
    

    before you use the reduce.

    0 讨论(0)
  • 2020-11-29 18:20

    Or if you use the six library

    from six.moves import reduce
    
    0 讨论(0)
  • 2020-11-29 18:22

    you need to install and import reduce from functools python package

    0 讨论(0)
提交回复
热议问题