使用xor()相当于sum()的Python

Cri*_*low 10 python sum xor

我喜欢Python sum函数:

>>> z = [1] * 11
>>> zsum = sum(z)
>>> zsum == 11
True
Run Code Online (Sandbox Code Playgroud)

我希望使用xor(^)而不是添加(+)具有相同的功能.我想用地图.但我无法弄清楚如何做到这一点.任何提示?

我对此不满意:

def xor(l):
    r = 0
    for v in l: r ^= v
    return v
Run Code Online (Sandbox Code Playgroud)

我想要使​​用地图的1班轮.提示?

Joh*_*ica 22

zxor = reduce(lambda a, b: a ^ b, z, 0)

import operator
zxor = reduce(operator.xor, z, 0)
Run Code Online (Sandbox Code Playgroud)


Xav*_*hot 5

请注意,从 开始,以及赋值表达式(PEP 572)(运算符)Python 3.8的引入,我们可以在列表推导式中使用和更新变量,从而将列表减少为其元素的异或::=

zxor = 0
[zxor := zxor ^ x for x in [1, 0, 1, 0, 1, 0]]
# zxor = 1
Run Code Online (Sandbox Code Playgroud)