<p><strong>从Python2.6开始(如果在Python3上),您有一个用于此功能的标准库工具:<a href="https://docs.python.org/2/library/itertools.html#itertools.permutations" rel="noreferrer">^{<cd1>}</a>。</p>
<pre><code>import itertools
list(itertools.permutations([1, 2, 3]))
</code></pre>
<hr/>
<p>如果您出于某种原因正在使用一个较旧的Python(<;2.6)</strong>,或者只是想知道它是如何工作的,那么这里有一个很好的方法,来自<a href="http://code.activestate.com/recipes/252178/" rel="noreferrer">http://code.activestate.com/recipes/252178/</a>:</p>
<pre><code>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:]
</code></pre>
<p>在<code>itertools.permutations</code>的文档中列出了两种替代方法。这里有一个:</p>
<pre><code>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
</code></pre>
<p>另一个,基于<code>itertools.product</code>:</p>
<pre><code>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)
</code></pre>