在列表中找到所有元组的组合

3

我正在尝试找到长度为2的列表中元组内部所有项目的排列组合。元组相对于彼此的顺序并不重要。

perm = [(3, 6), (6, 8), (4, 1), (7, 4), (5, 3),
        (1, 9), (2, 5), (4, 8), (5, 1), (3, 7),
        (6, 9), (10, 2), (7, 10), (8, 2), (9, 10)]

上述列表的一个排列示例如下:

一个这个列表的排列示例是:

perm = [(6, 3), (6, 8), (4, 1), (7, 4), (5, 3),
        (1, 9), (2, 5), (4, 8), (5, 1), (3, 7),
        (6, 9), (10, 2), (7, 10), (8, 2), (9, 10)]

另一个排列的示例如下:

perm = [(6, 3), (8, 6), (1, 4), (4, 7), (3, 5),
        (9, 1), (5, 2), (8, 4), (1, 5), (7, 3),
        (9, 6), (2, 10), (10, 7), (2, 8), (10, 9)]

最后,排列列表的长度应为32768,因为每个元组要么被交换,要么不被交换,而2^15 = 32768。我只关心元组之间的顺序,而不是元组中项目的排列。
我尝试过使用itertools的permute、combinations和product,但我没有获得期望的结果。
1个回答

4
你可以使用product:
from itertools import product

lst = [(3, 6), (6, 8), (4, 1), (7, 4), (5, 3),
       (1, 9), (2, 5), (4, 8), (5, 1), (3, 7),
       (6, 9), (10, 2), (7, 10), (8, 2), (9, 10)]

output = product(*([(x, y), (y, x)] for x, y in lst))

output = list(output) # if you want a list, rather than a generator

print(len(output))
# 32768

print(output[0])
# ((3, 6), (6, 8), (4, 1), (7, 4), (5, 3), (1, 9), (2, 5), (4, 8), (5, 1), (3, 7), (6, 9), (10, 2), (7, 10), (8, 2), (9, 10))
print(output[-1])
# ((6, 3), (8, 6), (1, 4), (4, 7), (3, 5), (9, 1), (5, 2), (8, 4), (1, 5), (7, 3), (9, 6), (2, 10), (10, 7), (2, 8), (10, 9))

关键在于编写类似以下内容的代码:

output = product([(3,6), (6,3)], [(6,8), (8,6)], ..., [(9,10), (10,9)])

通过生成器表达式和解包(*)的方式,以通用的方式处理任何输入列表。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接