📜  Python – 列表异或

📅  最后修改于: 2022-05-13 01:55:50.687000             🧑  作者: Mango

Python – 列表异或

有时,在编程时,我们可能需要在列表元素之间执行某些按位运算。这是一个必不可少的实用程序,因为我们多次遇到按位运算。让我们讨论可以执行 XOR 的某些方式。

方法 #1:使用reduce() + lambda + “^” operator
可以组合上述功能来执行此任务。我们可以使用 reduce() 来累积 lambda函数指定的 XOR 逻辑的结果。仅适用于 Python2。

# Python code to demonstrate working of
# List XOR
# Using reduce() + lambda + "^" operator
  
# initializing list
test_list = [4, 6, 2, 3, 8, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# List XOR
# Using reduce() + lambda + "^" operator
res = reduce(lambda x, y: x ^ y, test_list)
  
# printing result 
print("The Bitwise XOR of list elements are : " + str(res))
输出 :
The original list is : [4, 6, 2, 3, 8, 9]
The Bitwise XOR of list elements are : 2

方法 #2:使用reduce() + operator.ixor
也可以使用此方法执行此任务。在这种情况下,上述方法中由 lambda函数执行的任务是使用 ior函数进行累积异或运算的。仅适用于 Python2。

# Python code to demonstrate working of
# List XOR
# Using reduce() + operator.ixor
from operator import ixor
  
# initializing list
test_list = [4, 6, 2, 3, 8, 9]
  
# printing original list
print("The original list is : " + str(test_list))
  
# List XOR
# Using reduce() + operator.ixor
res = reduce(ixor, test_list)
  
# printing result 
print("The Bitwise XOR of list elements are : " + str(res))
输出 :
The original list is : [4, 6, 2, 3, 8, 9]
The Bitwise XOR of list elements are : 2