简体   繁体   English

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

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

I am trying to find all permutations of the items inside of the tuples while in the list of length 2. The order of the tuples in relation to each other does not matter.我试图在长度为 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)]

An example of one permutation of the above list would be:上述列表的一种排列的示例是:

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)]

Another example permutation would be:另一个示例排列是:

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)]

In the end, the length of the list of permutations should be 32768, because each tuple is either swapped or not swapped, and 2^15 = 32768. I do not care about the order of the tuples in relation to each other, only the permutations of the items inside of the tuples.最后,排列列表的长度应该是 32768,因为每个元组要么被交换,要么不被交换,并且 2^15 = 32768。我不关心元组相互之间的顺序,只关心元组内部项目的排列。

I have tried to use itertools permute, combinations, and product, but I haven't been able to get the desired result.我曾尝试使用 itertools permute、combinations 和 product,但一直无法得到想要的结果。

You can use 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))

The key is to write something like关键是写类似

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

in a generic way so that any input list would work, which is done by the generator expression and unpacking ( * ).以通用方式,以便任何输入列表都可以工作,这是由生成器表达式和解包 ( * ) 完成的。

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

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