2014-12-08 75 views
4

說我有一個列表:[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.permutations(),但我不知道如何產生的這部分[1],[2],[3],[1,2],[1,3],[2,3]名單。

謝謝!

+4

你刻意排除排列,如[2,1 ],[3,1],[3,2]? – mhawke 2014-12-08 02:50:59

回答

2

您的預期結果不包含所有可能的排列,因此不確定這是你想要的,或者你錯過了一些。但要獲得不同長度的列表的所有可能的排列,你可以做如下:

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