Python 中所有 N 个列表的排列组合
如果我们有两个列表,需要将第一个列表的每个元素与第二个列表的每个元素组合,那么我们可以使用以下方法。
使用 For 循环
在这种直接的方法中,我们创建一个包含每个列表元素排列组合的列表列表。我们设计了一个嵌套的 for 循环。内层循环对应第二个列表,外层循环对应第一个列表。
示例
A = [5,8]
B = [10,15,20]
print ("The given lists : ", A, B)
permutations = [[m, n] for m in A for n in B ]输出
运行以上代码,得到以下结果
The given lists : [5, 8] [10, 15, 20] permutations of the given values are : [[5, 10], [5, 15], [5, 20], [8, 10], [8, 15], [8, 20]]
使用 itertools
itertools 模块有一个名为 product 的迭代器。它与上述嵌套 for 循环的功能相同。在内部创建嵌套 for 循环以生成所需的乘积。
示例
import itertools
A = [5,8]
B = [10,15,20]
print ("The given lists : ", A, B)
result = list(itertools.product(A,B))
print ("permutations of the given lists are : " + str(result))输出
运行以上代码,得到以下结果
The given lists : [5, 8] [10, 15, 20] permutations of the given values are : [(5, 10), (5, 15), (5, 20), (8, 10), (8, 15), (8, 20)]
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP