您可以使用模块itertools。它默认包含在 Python 中(您不需要通过第三方模块安装它):
>>> import itertools
>>> print(itertools.permutations([1,2,3,4], 3))
[(1, 2, 3), (1, 2, 4), (1, 3, 2), (1, 3, 4), (1, 4, 2), (1, 4, 3), (2, 1, 3), (2, 1, 4), (2, 3, 1), (2, 3, 4), (2, 4, 1), (2, 4, 3), (3, 1, 2), (3, 1, 4), (3, 2, 1), (3, 2, 4), (3, 4, 1), (3, 4, 2), (4, 1, 2), (4, 1, 3), (4, 2, 1), (4, 2, 3), (4, 3, 1), (4, 3, 2)]
itertools.permutations(iterable, r=None) 生成给定可迭代元素(如列表)的所有可能排列。如果r 未指定或为None,则r 默认为可迭代的长度,并生成所有可能的全长排列。
如果您只寻找n pair 的排列而不是所有可能的排列,只需删除其余的排列:
>>> print(list(itertools.permutations([1,2,3,4], 3))[:3])
[(1, 2, 3), (1, 2, 4), (1, 3, 2)]
正如您在 cmets 中所要求的,您可以在不导入任何模块的情况下做到这一点。 itertools.permutations只是一个函数,你可以自己制作:
def permutations(iterable, r=None):
pool = tuple(iterable)
n = len(pool)
r = n if r is None else r
if r > n:
return
indices = list(range(n))
cycles = list(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
但我强烈建议您导入它。如果不想导入整个模块,只需要这个函数就可以了from itertools import permutations。