# 如何在 Python 中生成一个列表的所有排列

## 使用 `itertools.permutations` 在 Python 中生成一个列表的所有排列

Python 提供了一个标准的库工具 `itertools.permutation` 来生成排列。下面的例子展示了如何使用它来生成一个列表的所有排列。

``````import itertools
inp_list = [4, 5, 6]
permutations = list(itertools.permutations(inp_list))
print(permutations)
``````

``````[(4, 5, 6), (4, 6, 5), (5, 4, 6), (5, 6, 4), (6, 4, 5), (6, 5, 4)]
``````

``````import itertools
inp_list = [1, 2, 3]
permutations = list(itertools.permutations(inp_list, r=2))
print(permutations)
``````

``````[(4, 5), (4, 6), (5, 4), (5, 6), (6, 4), (6, 5)]
``````

``````import itertools
inp_list = [1, 2, 3]
permutations = []
for i in range(1,len(inp_list)+1):
permutations.extend(list(itertools.permutations(inp_list, r=i)))
print(permutations)
``````

``````[(4,), (5,), (6,), (4, 5), (4, 6), (5, 4), (5, 6), (6, 4), (6, 5), (4, 5, 6), (4, 6, 5), (5, 4, 6), (5, 6, 4), (6, 4, 5), (6, 5, 4)]
``````

## 使用递归在 Python 中生成列表的所有排列

``````def permutations(start, end=[]):
if len(start) == 0:
print(end)
else:
for i in range(len(start)):
permutations(start[:i] + start[i+1:], end + start[i:i+1])

permutations([4,5,6])
``````

``````[4, 5, 6]
[4, 6, 5]
[5, 4, 6]
[5, 6, 4]
[6, 4, 5]
[6, 5, 4]
``````

## 相关文章 - Python List

• 如何在 Python 中将列表转换为字符串
• Python 列表方法 append 和 extend 之间有什么区别
• comments powered by Disqus