เมื่อจำเป็นต้องแสดงรายการพจนานุกรมทั้งหมด จะใช้ความเข้าใจรายการอย่างง่ายและวิธีการ "zip" ร่วมกับวิธี "ผลิตภัณฑ์"
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ตัวอย่าง
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}] คำอธิบาย
-
แพ็คเกจที่จำเป็นจะถูกนำเข้าสู่สภาพแวดล้อม
-
สองรายการถูกกำหนดและแสดงบนคอนโซล
-
ผลิตภัณฑ์คาร์ทีเซียนของทั้งสองรายการคำนวณโดยใช้วิธี "ผลิตภัณฑ์"
-
ผลลัพธ์นี้ถูกกำหนดให้กับตัวแปร
-
ความเข้าใจรายการใช้เพื่อวนซ้ำรายการ และองค์ประกอบของรายการแรกและองค์ประกอบของตัวแปรที่กำหนดไว้ก่อนหน้านี้ใช้เพื่อสร้างพจนานุกรม
-
สิ่งนี้ถูกกำหนดให้กับตัวแปร
-
นี่คือเอาต์พุตที่แสดงบนคอนโซล