เมื่อต้องการแมปเมทริกซ์กับ dictionary ใช้การวนลูปง่าย
ตัวอย่าง
สาธิตด้านล่าง:
my_list = [[2, 4, 3], [4, 1, 3], [2, 1, 3, 4]]
print("The list :")
print(my_list)
map_dict = {2: "Python", 1: "fun", 3: "to", 4: "learn"}
my_result = []
for index in my_list:
temp = []
for element in index:
temp.append(map_dict[element])
my_result.append(temp)
print("The result is :")
print(my_result)
ผลลัพธ์
The list : [[2, 4, 3], [4, 1, 3], [2, 1, 3, 4]] The result is : [['Python', 'learn', 'to'], ['learn', 'fun', 'to'], ['Python', 'fun', 'to', 'learn']]
คำอธิบาย
- กำหนดลิสต์ของลิสต์และแสดงผล
- กำหนด dictionary สำหรับแมปค่า
- สร้างลิสต์ว่าง
- วนลูปลิสต์ นำ element จาก mapping dictionary append เข้า temp list
- append temp เข้า my_result
- แสดงผลลัพธ์บนคอนโซล