ถ้าเรามีสองลิสต์ และเราต้องการรวมแต่ละองค์ประกอบของลิสต์แรกกับแต่ละองค์ประกอบของลิสต์ที่สอง เรามีแนวทางดังต่อไปนี้
ใช้ For Loop
ในแนวทางตรงไปตรงมานี้ เราสร้างลิสต์ของลิสต์ที่มีการเรียงสลับขององค์ประกอบจากแต่ละลิสต์ เราออกแบบ for loop ภายใน for loop อีกทีหนึ่ง Inner for loop อ้างอิงถึงลิสต์ที่สอง และ Outer for loop อ้างอิงถึงลิสต์แรก
ตัวอย่าง
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 มี iterator ชื่อ product มันทำสิ่งเดียวกับ nested for loop ด้านบน สร้าง nested for loops ภายในเพื่อให้ผลคูณที่ต้องการ
ตัวอย่าง
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)]