问题描述
如何在Python中生成列表的所有排列,而与列表中元素的类型无关?
How do you generate all the permutations of a list in Python, independently of the type of elements in that list?
例如:
permutations([])
[]
permutations([1])
[1]
permutations([1, 2])
[1, 2]
[2, 1]
permutations([1, 2, 3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
推荐答案
从Python 2.6开始(如果您使用的是Python 3),则有一个 standard-library >为此的工具: itertools.permutations
.
Starting with Python 2.6 (and if you're on Python 3) you have a standard-library tool for this: itertools.permutations
.
import itertools
list(itertools.permutations([1, 2, 3]))
如果您出于某种原因使用旧版Python(,或者只是想知道它的工作原理,那么这是一种很好的方法,取材于 http://code.activestate.com/recipes/252178/:
If you're using an older Python (<2.6) for some reason or are just curious to know how it works, here's one nice approach, taken from http://code.activestate.com/recipes/252178/:
def all_perms(elements):
if len(elements) <=1:
yield elements
else:
for perm in all_perms(elements[1:]):
for i in range(len(elements)):
# nb elements[0:1] works in both string and list contexts
yield perm[:i] + elements[0:1] + perm[i:]
itertools.permutations
的文档中列出了几种替代方法.这是一个:
A couple of alternative approaches are listed in the documentation of itertools.permutations
. Here's one:
def permutations(iterable, r=None):
# permutations('ABCD', 2) --> AB AC AD BA BC BD CA CB CD DA DB DC
# permutations(range(3)) --> 012 021 102 120 201 210
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = range(n)
cycles = range(n, n-r, -1)
yield tuple(pool[i] for i in indices[:r])
while n:
for i in reversed(range(r)):
cycles[i] -= 1
if cycles[i] == 0:
indices[i:] = indices[i+1:] + indices[i:i+1]
cycles[i] = n - i
else:
j = cycles[i]
indices[i], indices[-j] = indices[-j], indices[i]
yield tuple(pool[i] for i in indices[:r])
break
else:
return
另一个基于itertools.product
:
def permutations(iterable, r=None):
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
for indices in product(range(n), repeat=r):
if len(set(indices)) == r:
yield tuple(pool[i] for i in indices)
这篇关于如何生成列表的所有排列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!