python - 遍历适合特定键的排列

标签 python algorithm permutation python-itertools

想象一些列表

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

等等

现在我只是遍历所有 排列,并且只采用适合 key 的排列,但这会浪费很多时间和排列。我更愿意直接生成我需要的东西,但我根本不知道该怎么做,尽管更深入地研究了 itertools。

最佳答案

你可以spearately构建不同长度的元组的排列并将它们组合起来:

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]

关于python - 遍历适合特定键的排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26488073/

相关文章:

python - 如何阻塞主线程直到所有其他线程执行完毕?

带有 Twisted 的 Python Web 服务

python - 如何检测python代码中的内存泄漏?

algorithm - 在 Matlab 中检测视频镜头变化

Prolog 排列颜色适量的组合错误

r - 如何在R中生成N个最不相似的组合

c++ - 需要参数的函数无需参数即可工作 (C++)

python - 按值从多个列表中删除出现的元素(缩短多个列表)

java - 返回所有矩形的并集

algorithm - 近似最近对算法