想象一下列表
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。
答案 0 :(得分:4)
你可以组织不同长度的元组的排列并将它们组合起来:
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]