繁体   English   中英

查找列表内的所有元组组合

[英]Find all combinations of tuples inside of a list

我试图在长度为 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,但一直无法得到想要的结果。

您可以使用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)])

以通用方式,以便任何输入列表都可以工作,这是由生成器表达式和解包 ( * ) 完成的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM