gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:23:24 24 4
gpt4 key购买 nike

想象一些列表

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com