如何在python中配对两个元组?

may*_*mov -2 python

我需要构建一个接受2个元组的函数,并将它们与所有可能的对配对。

例如,我需要带元组:

first_tuple = (1, 2)
second_tuple = (4, 5)
Run Code Online (Sandbox Code Playgroud)

结果必须是:

((1, 4), (4, 1), (1, 5), (5, 1), (2, 4), (4, 2), (2, 5), (5, 2))
Run Code Online (Sandbox Code Playgroud)

Net*_*ave 7

您可以使用itertools.productitertools.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)]
Run Code Online (Sandbox Code Playgroud)

对于任意的元组大小,您可以使用(@ Aran-Fei思想):

[perm for tup in half for perm in itertools.permutations(tup)]
Run Code Online (Sandbox Code Playgroud)

  • 如果要支持任意数量的输入元组而不是仅支持两个,则最后一行可以更改为[[itertools.permutations(tup)中perm占一半,perm占一半]。 (2认同)