2013-11-21 47 views
0

我有一個列表獲取從列表中的所有組合,有和沒有重複

a = ['a', 'b', 'c'] 

如何,我可以重複獲得所有組合,沒有他們從這個名單。 最終的輸出是:

[('a', 'b', 'c'), 
('a', 'c', 'b'), 
('b', 'a', 'c'), 
('b', 'c', 'a'), 
('c', 'a', 'b'), 
('c', 'b', 'a')] 
+2

信息:這稱爲排列。你可以在谷歌上搜索它。 – aIKid

回答

4

使用itertools.permutations

>>> import itertools 
>>> a = ['a', 'b', 'c'] 
>>> list(itertools.permutations(a)) 
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), ('c', 'a', 'b'), ('c', 'b', 'a')] 
0

使用permutations功能從itertools

from itertools import permutations 
x = list(itertools.permutations(a)) 

以上列表不會被字典順序排序。如果給定的輸入列表被排序,那麼輸出列表將被排序。否則,您必須使用手動對列表進行分類x.sort()