Python中N个列表的所有可能排列
如果我们有两个列表,并且需要将第一个元素的每个元素与第二个列表的每个元素组合在一起,那么我们可以采用以下方法。
使用For循环
在这种简单的方法中,我们创建了一个列表列表,其中包含每个列表中元素的排列。我们在另一个for循环中设计一个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)]
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿