📜  Python|元组中的元素与

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

Python|元组中的元素与

有时,在处理记录时,我们可能会遇到需要跨元组执行数学按位与运算的问题。在白天编程中可能会出现此问题。让我们讨论可以执行此任务的某些方式。

方法 #1:使用zip() + 生成器表达式
上述功能的组合可用于执行此任务。在此,我们使用生成器表达式执行 AND 的任务,每个元组的映射索引由 zip() 完成。

# Python3 code to demonstrate working of 
# Elementwise AND in tuples
# using zip() + generator expression 
  
# initialize tuples 
test_tup1 = (10, 4, 6, 9) 
test_tup2 = (5, 2, 3, 3) 
  
# printing original tuples 
print("The original tuple 1 : " + str(test_tup1)) 
print("The original tuple 2 : " + str(test_tup2)) 
  
# Elementwise AND in tuples
# using zip() + generator expression 
res = tuple(ele1 & ele2 for ele1, ele2 in zip(test_tup1, test_tup2)) 
  
# printing result 
print("The AND tuple : " + str(res)) 
输出 :
The original tuple 1 : (10, 4, 6, 9)
The original tuple 2 : (5, 2, 3, 3)
The AND tuple : (0, 0, 2, 1)

方法 #2:使用map() + iand
上述功能的组合也可以执行此任务。在此,我们使用 iand 执行扩展 AND 逻辑的任务,映射由 map() 完成。

# Python3 code to demonstrate working of 
# Elementwise AND in tuples 
# using map() + iand 
from operator import iand 
  
# initialize tuples 
test_tup1 = (10, 4, 6, 9) 
test_tup2 = (5, 2, 3, 3) 
  
# printing original tuples 
print("The original tuple 1 : " + str(test_tup1)) 
print("The original tuple 2 : " + str(test_tup2)) 
  
# Elementwise AND in tuples 
# using map() + iand
res = tuple(map(iand, test_tup1, test_tup2)) 
  
# printing result 
print("The AND tuple : " + str(res)) 
输出 :
The original tuple 1 : (10, 4, 6, 9)
The original tuple 2 : (5, 2, 3, 3)
The AND tuple : (0, 0, 2, 1)