Python – 2 个元组的所有对组合
有时,在处理Python元组数据时,我们可能会遇到需要提取 2 个参数元组的所有可能组合的问题。这种应用程序可以出现在数据科学或游戏领域。让我们讨论可以执行此任务的某些方式。
Input : test_tuple1 = (7, 2), test_tuple2 = (7, 8)
Output : [(7, 7), (7, 8), (2, 7), (2, 8), (7, 7), (7, 2), (8, 7), (8, 2)]
Input : test_tuple1 = (9, 2), test_tuple2 = (7, 8)
Output : [(9, 7), (9, 8), (2, 7), (2, 8), (7, 9), (7, 2), (8, 9), (8, 2)]
方法#1:使用列表推导
这是可以执行此任务的方式之一。在这个过程中,我们在一个 pass 中执行形成一个索引组合的任务,在另一个 pass 中更改索引,并添加到初始结果列表中。
# Python3 code to demonstrate working of
# All pair combinations of 2 tuples
# Using list comprehension
# initializing tuples
test_tuple1 = (4, 5)
test_tuple2 = (7, 8)
# printing original tuples
print("The original tuple 1 : " + str(test_tuple1))
print("The original tuple 2 : " + str(test_tuple2))
# All pair combinations of 2 tuples
# Using list comprehension
res = [(a, b) for a in test_tuple1 for b in test_tuple2]
res = res + [(a, b) for a in test_tuple2 for b in test_tuple1]
# printing result
print("The filtered tuple : " + str(res))
输出 :
The original tuple 1 : (4, 5)
The original tuple 2 : (7, 8)
The filtered tuple : [(4, 7), (4, 8), (5, 7), (5, 8), (7, 4), (7, 5), (8, 4), (8, 5)]
方法#2:使用chain() + product()
上述功能的组合提供了另一种解决此问题的方法。在此,我们使用 product() 执行配对创建任务,chain() 用于将 product() 的结果相加两次。
# Python3 code to demonstrate working of
# All pair combinations of 2 tuples
# Using chain() + product()
from itertools import chain, product
# initializing tuples
test_tuple1 = (4, 5)
test_tuple2 = (7, 8)
# printing original tuples
print("The original tuple 1 : " + str(test_tuple1))
print("The original tuple 2 : " + str(test_tuple2))
# All pair combinations of 2 tuples
# Using chain() + product()
res = list(chain(product(test_tuple1, test_tuple2), product(test_tuple2, test_tuple1)))
# printing result
print("The filtered tuple : " + str(res))
输出 :
The original tuple 1 : (4, 5)
The original tuple 2 : (7, 8)
The filtered tuple : [(4, 7), (4, 8), (5, 7), (5, 8), (7, 4), (7, 5), (8, 4), (8, 5)]