Python – 列表的按位与
有时,在编程时,我们可能需要在列表元素之间执行某些按位运算。这是一个必不可少的实用程序,因为我们多次遇到按位运算。让我们讨论可以执行此任务的某些方式。
方法 #1:使用 reduce() + lambda + “&”运算符
可以组合上述功能来执行此任务。我们可以使用 reduce() 来累积 lambda函数指定的 AND 逻辑的结果。仅适用于 Python2。
Python3
# Python code to demonstrate working of
# Bitwise AND of List
# 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))
# Bitwise AND of List
# Using reduce() + lambda + "&" operator
res = reduce(lambda x, y: x & y, test_list)
# printing result
print("The Bitwise AND of list elements are : " + str(res))
Python3
# Python code to demonstrate working of
# Bitwise AND of List
# Using functools.reduce() + operator.iand
from operator import iand
from functools import reduce
# initializing list
test_list = [4, 6, 2, 3, 8, 9]
# printing original list
print("The original list is : " + str(test_list))
# Bitwise AND of List
# Using functools.reduce() + operator.iand
res = reduce(iand, test_list)
# printing result
print("The Bitwise AND of list elements are : " + str(res))
输出 :
The original list is : [4, 6, 2, 3, 8, 9]
The Bitwise AND of list elements are : 0
方法 #2:使用 reduce() +运算符.iand
也可以使用此方法执行此任务。在这种情况下,上述方法中由 lambda函数执行的任务是使用 iand函数进行累积与运算的。仅适用于 Python2。
Python3
# Python code to demonstrate working of
# Bitwise AND of List
# Using functools.reduce() + operator.iand
from operator import iand
from functools import reduce
# initializing list
test_list = [4, 6, 2, 3, 8, 9]
# printing original list
print("The original list is : " + str(test_list))
# Bitwise AND of List
# Using functools.reduce() + operator.iand
res = reduce(iand, test_list)
# printing result
print("The Bitwise AND of list elements are : " + str(res))
输出 :
The original list is : [4, 6, 2, 3, 8, 9]
The Bitwise AND of list elements are : 0