เมื่อต้องการสร้างการจัดหมู่ (combinations) ทั้งหมดของลิสต์ dictionary จากสองลิสต์ สามารถใช้ list comprehension, zip() และ itertools.product() ได้
ตัวอย่าง
from itertools import product
my_list_1 = ["python", "is", "fun"]
my_list_2 = [24, 15]
print("The first list is :")
print(my_list_1)
print("The second list is :")
print(my_list_2)
temp = product(my_list_2, repeat=len(my_list_1))
my_result = [{key: value for (key, value) in zip(my_list_1, element)} for element in temp]
print("The result is :")
print(my_result)
ผลลัพธ์
The first list is : ['python', 'is', 'fun']
The second list is : [24, 15]
The result is : [{'python': 24, 'is': 24, 'fun': 24}, {'python': 24, 'is': 24, 'fun': 15}, {'python': 24, 'is': 15, 'fun': 24}, {'python': 24, 'is': 15, 'fun': 15}, {'python': 15, 'is': 24, 'fun': 24}, {'python': 15, 'is': 24, 'fun': 15}, {'python': 15, 'is': 15, 'fun': 24}, {'python': 15, 'is': 15, 'fun': 15}]
คำอธิบาย
นำเข้า
productจากitertoolsกำหนดลิสต์ key (my_list_1) และลิสต์ค่า (my_list_2)
ใช้
product(my_list_2, repeat=len(my_list_1))สร้าง cartesian product ของค่า ทุกการจัดเรียงเป็นไปได้ใช้ list comprehension +
zip()จับคู่ key กับค่าแต่ละชุด สร้าง dictionaryแสดงผลลัพธ์ลิสต์ของ dictionary ทุกการจัดหมู่ที่เป็นไปได้ (2^3 = 8 แบบ)