📜  Python – 元组列表中的交叉配对

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

Python – 元组列表中的交叉配对

给定 2 个元组,执行对应元组的交叉配对,如果两个元组的第一个元素匹配,则转换为单个元组。

方法#1:使用列表推导

在此,我们使用条件语句检查第一个元素,并在列表理解中构造新元组。

Python3
# Python3 code to demonstrate working of 
# Cross Pairing in Tuple List
# Using list comprehension
  
# initializing lists
test_list1 = [(1, 7), (6, 7), (9, 100), (4, 21)]
test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]
  
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# corresponding loop in list comprehension
res = [(sub1[1], sub2[1]) for sub2 in test_list2 for sub1 in test_list1 if sub1[0] == sub2[0]]
  
# printing result 
print("The mapped tuples : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Cross Pairing in Tuple List
# Using zip() + list comprehension
  
# initializing lists
test_list1 = [(1, 7), (6, 7), (9, 100), (4, 21)]
test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]
  
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# zip() is used for pairing 
res = [(a[1], b[1]) for a, b in zip(test_list1, test_list2) if a[0] == b[0]]
  
# printing result 
print("The mapped tuples : " + str(res))


输出
The original list 1 : [(1, 7), (6, 7), (9, 100), (4, 21)]
The original list 2 : [(1, 3), (2, 1), (9, 7), (2, 17)]
The mapped tuples : [(7, 3), (100, 7)]

方法 #2:使用 zip() + 列表理解

在这种情况下,配对任务是使用 zip() 完成的,条件检查是在列表理解中完成的。

Python3

# Python3 code to demonstrate working of 
# Cross Pairing in Tuple List
# Using zip() + list comprehension
  
# initializing lists
test_list1 = [(1, 7), (6, 7), (9, 100), (4, 21)]
test_list2 = [(1, 3), (2, 1), (9, 7), (2, 17)]
  
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# zip() is used for pairing 
res = [(a[1], b[1]) for a, b in zip(test_list1, test_list2) if a[0] == b[0]]
  
# printing result 
print("The mapped tuples : " + str(res))
输出
The original list 1 : [(1, 7), (6, 7), (9, 100), (4, 21)]
The original list 2 : [(1, 3), (2, 1), (9, 7), (2, 17)]
The mapped tuples : [(7, 3), (100, 7)]