如何在 Python 中生成一個列表的所有排列
Hassan Saeed 2023年1月30日 Python Python List

本教程討論了在 Python 中生成一個列表的所有排列的方法。
在 Python 中使用 itertools.permutations
生成一個列表的所有排列
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)]
預設的排列的長度被設定為輸入列表的長度。然而,我們可以在 itertools.permutations
函式呼叫中指定組合的長度。下面的例子說明了這一點。
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 中使用遞迴生成列表的所有排列
我們也可以在 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]
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe