2012-01-27 86 views
6

我有一個列表[2,3,4]。我如何在列表中找到所有可能的元素序列? 因此,輸出應爲: [2,3,4] [2,4,3] [3,2,4] [3,4,2] [4,2,3] [4 1,3,2]如何在列表中查找所有可能的元素序列?

+0

可能重複[如何產生的所有排列在Python中的列表](http://stackoverflow.com/questions/104420/how-to-generate-all-permutations-of-a-list-in-python) – 2012-01-30 07:33:53

回答

21

爲此,您可以輕鬆地使用itertools.permutations()

>>> from itertools import permutations 
>>> list(permutations([2, 3, 4])) 
[(2, 3, 4), (2, 4, 3), (3, 2, 4), (3, 4, 2), (4, 2, 3), (4, 3, 2)] 

如果因爲某些原因,你需要列出,而不是元組:

>>> map(list, permutations([2, 3, 4])) 
[[2, 3, 4], [2, 4, 3], [3, 2, 4], [3, 4, 2], [4, 2, 3], [4, 3, 2]] 
+3

希望OP列表具有所有獨特的元素。 – Droogans 2012-01-27 22:34:43

+1

也許添加一個鏈接到http://docs.python.org/library/itertools.html#itertools.permutations? – 2012-01-27 22:37:36

5

您正在尋找permutati插件,這樣的事情應該工作:

import itertools 
itertools.permutations([2,3,4]) 
2

除了數據的大抽籤程序的啓動會被格式化爲這樣

ist(permutations([2, 3, 4],[7,2,5],[8,1,4,9])) 

的問題是,第一組用於創建第一號列僅 的謝勝利爲2列和第3爲第三

的輸出將是一組3個數字的只是置換是不同

1

只要你知道:

def unique_perms(elems): 
    """returns non-duplicate permutations 
     if duplicate elements exist in `elems` 
    """ 
    from itertools import permutations 
    return list(set(permutations(elems))) 

但是,如果你正在做這樣的事情:

print len(unique_perms(elems)) 

然後嘗試這樣的:

def fac(n): 
    """n!""" 
    if n == 1: return n 
    return n * fac(n -1) 

def unique_perm_count(elems) 
    n = len(elems) 
    return fac(2 * n)/fac(n) ** 2 
相關問題