简体   繁体   English

生成列表的所有排列和该列表中可能列表的排列?

[英]Generate all permutations of a list and permutations of the possible lists within that list?

Say I had a list: [1,2,3] 说我有一个清单: [1,2,3]

How would I generate: 我将如何生成:

[[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

I know how to use itertools.permutations(), but I don't know how to generate this portion [1],[2],[3],[1,2],[1,3],[2,3] of the list. 我知道如何使用itertools.permutations(),但我不知道如何生成这部分[1],[2],[3],[1,2],[1,3],[2,3]列表。

Thanks! 谢谢!

Your expected result does not contain all possible permutations, so not sure this is what you want, or you missed some. 您的预期结果不包含所有可能的排列,因此不确定这是您想要的,或者您错过了一些。 But to get all possible permutations of a list of different lengths, you can do as follows: 但要获得不同长度列表的所有可能排列,您可以执行以下操作:

from itertools import permutations
a_list = [1,2,3]
perm_list = [p for l in range(1, len(a_list)+1) for p in permutations(a_list,l)]
print(perm_list)

The result is: 结果是:

[(1,), (2,), (3,), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

If the input list is large though, probably it would be better to use generator expression, eg 如果输入列表很大,可能最好使用生成器表达式,例如

perm_list_gen = (p for l in range(1, len(a_list)+1) for p in permutations(a_list,l))
print(perm_list_gen)
#prints:  <generator object <genexpr> at 0x7f176bbd88b8>

And than just go one by one, instead of everything at once: 而不是一个一个地去,而不是一次一个:

for perm in perm_list_gen:
    print(perm)
from itertools import permutations
lst = [1, 2, 3]
per = list(permutations(lst, 1)) + list(permutations(lst, 2)) + list(permutations(lst, 3))

output: 输出:

>>> [(1,), (2,), (3,), (1, 2), (1, 3), (2, 1), (2, 3), (3, 1), (3, 2), (1, 2, 3), (1, 3, 2), (2, 1, 3), (2, 3, 1), (3, 1, 2), (3, 2, 1)]

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

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