list/tuple 的元素的异或
xor of elements of a list/tuple
我有一个 '0'
和 '1'
的元组,我想要它所有元素的异或。比如我有('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)
我怎样才能以更 pythonic 的方式制作它(使用 map
和 lambda 函数?)
print reduce(lambda i, j: int(i) ^ int(j), bit)
reduce(...) reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence,
from left to right, so as to reduce the sequence to a single value.
For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates
((((1+2)+3)+4)+5). If initial is present, it is placed before the items
of the sequence in the calculation, and serves as a default when the
sequence is empty.
如前所述,reduce
效果很好。如果您阅读 reduce
,您会遇到 fold 的概念,它是高阶函数(如 map
)。
在某些语言中,您可以向左或向右折叠。有趣的是,在你的情况下,如果你从左边或右边开始,你会得到相同的结果,因为 xor
是交换和结合的。
在Python3中你可以使用:
>>> from functools import reduce
>>> from operator import xor
>>> bits = ('0', '1', '0', '1', '0', '1', '0')
>>> reduce(xor, map(int, bits))
1
或者如果你想要一个 运行 XOR:
>>> 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]
如果您正在寻找不使用 reduce 或 lambda 的解决方案,请看看这个版本
函数
A = [1,1,2,3,4,4,5,5]
x = 0
for i in A:
x ^= i
print(x)
output : 3
我有一个 '0'
和 '1'
的元组,我想要它所有元素的异或。比如我有('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)
我怎样才能以更 pythonic 的方式制作它(使用 map
和 lambda 函数?)
print reduce(lambda i, j: int(i) ^ int(j), bit)
reduce(...) reduce(function, sequence[, initial]) -> value
Apply a function of two arguments cumulatively to the items of a sequence, from left to right, so as to reduce the sequence to a single value. For example, reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) calculates ((((1+2)+3)+4)+5). If initial is present, it is placed before the items of the sequence in the calculation, and serves as a default when the sequence is empty.
如前所述,reduce
效果很好。如果您阅读 reduce
,您会遇到 fold 的概念,它是高阶函数(如 map
)。
在某些语言中,您可以向左或向右折叠。有趣的是,在你的情况下,如果你从左边或右边开始,你会得到相同的结果,因为 xor
是交换和结合的。
在Python3中你可以使用:
>>> from functools import reduce
>>> from operator import xor
>>> bits = ('0', '1', '0', '1', '0', '1', '0')
>>> reduce(xor, map(int, bits))
1
或者如果你想要一个 运行 XOR:
>>> 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]
如果您正在寻找不使用 reduce 或 lambda 的解决方案,请看看这个版本 函数
A = [1,1,2,3,4,4,5,5]
x = 0
for i in A:
x ^= i
print(x)
output : 3