我需要构建一个包含2个元组的函数,并将它们配对为所有可能的对。
例如,我需要学习元组:
first_tuple = (1, 2)
second_tuple = (4, 5)
结果必须是:
((1, 4), (4, 1), (1, 5), (5, 1), (2, 4), (4, 2), (2, 5), (5, 2))
答案 0 :(得分:7)
您可以使用itertools.product
和itertools.chain
,其想法是接受所有可能的产品订购,并且由于元组的大小为2,因此只需要翻转它们即可:
>>> from itertools import product, chain
>>> first_tuple = (1, 2)
>>> second_tuple = (4, 5)
>>> half = list(product(first_tuple, second_tuple))
>>> half
[(1, 4), (1, 5), (2, 4), (2, 5)]
>>> list(chain(half, map(lambda x: (x[1], x[0]), half)))
[(1, 4), (1, 5), (2, 4), (2, 5), (4, 1), (5, 1), (4, 2), (5, 2)]
对于任意的元组大小,您可以使用(@ Aran-Fei想法):
[perm for tup in half for perm in itertools.permutations(tup)]
答案 1 :(得分:3)
您首先要使用itertools.product创建初始配对,然后使用该配对创建另一个配对,其中元组元素将被交换
from itertools import product
first_tuple = (1, 2)
second_tuple = (4, 5)
#First pairing
prod_1 = list(product(first_tuple, second_tuple))
#Pairing with swapped positions of tuple
prod_2 = [(t[1], t[0]) for t in prod_1]
#Final output
res = prod_1 + prod_2
print(res)
输出将为
[(1, 4), (1, 5), (2, 4), (2, 5), (4, 1), (5, 1), (4, 2), (5, 2)]
答案 2 :(得分:0)
from itertools import chain,product
first_tuple = (1, 2)
second_tuple = (4, 5)
combined = list(chain(*[[(f,s),(s,f)] for f in first_tuple for s in second_tuple]))
print (combined)
输出:
[(1, 4), (4, 1), (1, 5), (5, 1), (2, 4), (4, 2), (2, 5), (5, 2)]
。
itertools.product()
此工具计算输入可迭代项的笛卡尔积。它是 等效于嵌套的for循环。例如,product(A,B)返回 与(A中x等于B中y等于((x,y))。
要获得所需列表的第一部分是:
list(product(first_tuple, second_tuple)) # (1, 4), (4, 1), (1, 5), (5, 1)
第二部分足以反转:
list(product(second_tuple, first_tuple)) # (2, 4), (4, 2), (2, 5), (5, 2)
。
combined1 = list(product(first_tuple, second_tuple)) + list(product(second_tuple, first_tuple))
print (combined1)
输出:
[(1, 4), (1, 5), (2, 4), (2, 5), (4, 1), (4, 2), (5, 1), (5, 2)]