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

Hassan Saeed 2023年1月30日 Python Python List
  1. 在 Python 中使用 itertools.permutations 生成一个列表的所有排列
  2. 在 Python 中使用递归生成列表的所有排列
如何在 Python 中生成一个列表的所有排列

本教程讨论了在 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

相关文章 - Python List