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)]
廣告