Cho N list, tạo tất cả tổ hợp lấy một phần tử từ mỗi list (tích Descartes).
Dùng vòng lặp for
List comprehension lồng: [[m,n] for m in A for n in B].
Ví dụ
A = [5,8]
B = [10,15,20]
print ("The given lists : ", A, B)
permutations = [[m, n] for m in A for n in B ] Đầu ra
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]]
Dùng itertools
itertools.product() làm tương tự.
Ví dụ
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)) Đầu ra
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)]