迭代适合特定键的排列

想象一下列表

L = [(1,2,3),(4,5,6),(7,8),(9,10),(11,12,13)]

我想遍历这个列表的所有排列,这些排列适合任意长度的关键字,如(2,2,3,3,3)

所以在这种情况下,元素的长度适合该键的所有排列。

[(7,8),(9,10),(1,2,3),(4,5,6),(11,12,13)]

[(9,10),(7,8),(1,2,3),(4,5,6),(11,12,13)]

[(7,8),(9,10),(4,5,6),(1,2,3),(11,12,13)]

等等

现在,我只是遍历所有的排列组合,只是采用适合关键字的排列,但是这经历了很多浪费时间和排列。 尽管更深入地研究itertools,我宁愿直接生成我所需要的东西,但我不知道如何去做。


您可以精确地构建不同长度的元组的排列,并将它们组合在一起:

from itertools import chain, permutations, product
tuples_by_length = {}
for t in L:
    tuples_by_length.setdefault(len(t), []).append(t)
for x, y in product(permutations(tuples_by_length[2]),
                    permutations(tuples_by_length[3])):
    print list(chain(x, y))

输出:

[(7, 8), (9, 10), (1, 2, 3), (4, 5, 6), (11, 12, 13)]
[(7, 8), (9, 10), (1, 2, 3), (11, 12, 13), (4, 5, 6)]
[(7, 8), (9, 10), (4, 5, 6), (1, 2, 3), (11, 12, 13)]
[(7, 8), (9, 10), (4, 5, 6), (11, 12, 13), (1, 2, 3)]
[(7, 8), (9, 10), (11, 12, 13), (1, 2, 3), (4, 5, 6)]
[(7, 8), (9, 10), (11, 12, 13), (4, 5, 6), (1, 2, 3)]
[(9, 10), (7, 8), (1, 2, 3), (4, 5, 6), (11, 12, 13)]
[(9, 10), (7, 8), (1, 2, 3), (11, 12, 13), (4, 5, 6)]
[(9, 10), (7, 8), (4, 5, 6), (1, 2, 3), (11, 12, 13)]
[(9, 10), (7, 8), (4, 5, 6), (11, 12, 13), (1, 2, 3)]
[(9, 10), (7, 8), (11, 12, 13), (1, 2, 3), (4, 5, 6)]
[(9, 10), (7, 8), (11, 12, 13), (4, 5, 6), (1, 2, 3)]

这种方法可以推广到任意长度的键:

def permutations_with_length_key(lst, length_key):
    tuples_by_length = {}
    for t in L:
        tuples_by_length.setdefault(len(t), []).append(t)
    positions = {k: i for i, k in enumerate(tuples_by_length.iterkeys())}
    for x in product(*[permutations(v) for v in tuples_by_length.itervalues()]):
        x = map(iter, x)
        yield [next(x[positions[y]]) for y in length_key]
链接地址: http://www.djcxy.com/p/24321.html

上一篇: Iterating through permutations that fit a specific key

下一篇: Recursive permutations in Haskell