列表/元组的元素的xor

Sha*_*n-x 3 python xor

我有一个'0'和的元组'1',我想要它的所有元素的xor.例如,如果我有('0', '1', '1', '0'),我想获得((0 xor 1) xor 1) xor 0.

我有以下(工作)片段:

bit = ('0', '1', '0', '1', '0', '1', '0')
out = bit[0]
for i in range(1, len(bit)):
    out = int(out) ^ int(bit[i])
print str(out)
Run Code Online (Sandbox Code Playgroud)

我怎么能用更pythonic ay(使用map和lambda函数?)

zep*_*hor 9

print reduce(lambda i, j: int(i) ^ int(j), bit)
Run Code Online (Sandbox Code Playgroud)

reduce(...)reduce(function,sequence [,initial]) - > value

从左到右累加两个参数的函数到序列的项目,以便将序列减少为单个值.例如,reduce(lambda x,y:x + y,[1,2,3,4,5])计算(((((1 + 2)+3)+4)+5).如果存在initial,则将其放在计算中序列的项之前,并在序列为空时用作默认值.

  • 必须首先导入“reduce”:“from functools import reduce” (2认同)

Eug*_*ash 5

在 Python 3 中你可以使用:

>>> from functools import reduce
>>> from operator import xor
>>> bits = ('0', '1', '0', '1', '0', '1', '0')
>>> reduce(xor, map(int, bits))
1
Run Code Online (Sandbox Code Playgroud)

或者,如果您想要运行异或:

>>> from itertools import accumulate
>>> from operator import xor
>>> bits = ('0', '1', '0', '1', '0', '1', '0')
>>> list(accumulate(map(int, bits), xor))
[0, 1, 1, 0, 0, 1, 1]
Run Code Online (Sandbox Code Playgroud)