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

2024-04-24 10:33:44 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个列表:[1,2,3]

如何生成:

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

我知道如何使用itertools.排列(),但我不知道如何生成列表的这部分[1],[2],[3],[1,2],[1,3],[2,3]。你知道吗

谢谢!你知道吗


Tags: 列表itertools
2条回答
from itertools import permutations
lst = [1, 2, 3]
per = list(permutations(lst, 1)) + list(permutations(lst, 2)) + list(permutations(lst, 3))

输出:

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

您的预期结果不包含所有可能的排列,因此不确定这是您想要的,或者您错过了一些。但要获得不同长度列表的所有可能排列,可以执行以下操作:

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)

结果是:

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

如果输入列表很大,可能最好使用生成器表达式,例如

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>

而不是一个接一个地走,而不是一下子走:

for perm in perm_list_gen:
    print(perm)

相关问题 更多 >