📜  Python – 元组之间的 AND 操作

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

Python – 元组之间的 AND 操作

有时,在处理记录时,我们可能会遇到一个常见问题,即对一个元组的内容与另一个元组的相应索引进行 AND 运算。这几乎适用于我们处理元组记录的所有领域,尤其是数据科学。让我们讨论可以执行此任务的某些方式。

方法 #1:使用map() + lambda
结合以上功能可以为我们解决问题。在此,我们使用 lambda 函数计算 AND,并使用 map() 将逻辑扩展到键。

# Python3 code to demonstrate working of
# Cross Tuple AND operation
# using map() + lambda
  
# initialize tuples 
test_tup1 = (10, 4, 5)
test_tup2 = (2, 5, 18)
  
# printing original tuples 
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
  
# Cross Tuple AND operation
# using map() + lambda
res = tuple(map(lambda i, j: i & j, test_tup1, test_tup2))
  
# printing result
print("Resultant tuple after AND operation : " + str(res))
输出 :
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (2, 5, 18)
Resultant tuple after AND operation : (2, 4, 0)

方法 #2:使用map() + iand()
以上功能的组合可以帮助我们完成这个任务。在此,我们首先使用 map() 将逻辑扩展到所有,然后使用 iand() 对每个索引执行 AND。

# Python3 code to demonstrate working of
# Cross Tuple AND operation
# using map() + iand()
import operator
  
# initialize tuples 
test_tup1 = (10, 4, 5)
test_tup2 = (2, 5, 18)
  
# printing original tuples 
print("The original tuple 1 : " + str(test_tup1))
print("The original tuple 2 : " + str(test_tup2))
  
# Cross Tuple AND operation
# using map() + iand()
res = tuple(map(operator.iand, test_tup1, test_tup2))
  
# printing result
print("Resultant tuple after AND operation : " + str(res))
输出 :
The original tuple 1 : (10, 4, 5)
The original tuple 2 : (2, 5, 18)
Resultant tuple after AND operation : (2, 4, 0)