我有一个列表[2,3,4],如何找到列表中所有可能的元素序列?输出结果应该是: [2,3,4] [2,4,3] [3,2,4] [3,4,2] [4,2,3] [4,3,2]
我有一个列表[2,3,4],如何找到列表中所有可能的元素序列?输出结果应该是: [2,3,4] [2,4,3] [3,2,4] [3,4,2] [4,2,3] [4,3,2]
你可以轻松地使用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]]
import itertools
itertools.permutations([2,3,4])
ist(permutations([2, 3, 4],[7,2,5],[8,1,4,9]))
只是让你知道:
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