เมื่อต้องการนับคู่ของสตริงย้อนกลับ จะใช้การวนซ้ำอย่างง่าย
ตัวอย่าง
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน
my_list = [{"Python": 8, "is": 1, "fun": 9}, {"Python": 2, "is": 9, "fun": 1}, {"Python": 5, "is": 10,"fun": 7}]
print("The list is :")
print(my_list)
result = {}
for dic in my_list:
for key, value in dic.items():
if key in result:
result[key] = max(result[key], value)
else:
result[key] = value
print("The result is :")
print(result) ผลลัพธ์
The list is :
[{'Python': 8, 'is': 1, 'fun': 9}, {'Python': 2, 'is': 9, 'fun': 1}, {'Python': 5, 'is': 10, 'fun': 7}]
The result is :
{'Python': 8, 'is': 10, 'fun': 9} คำอธิบาย
-
รายการพจนานุกรมถูกกำหนดและแสดงบนคอนโซล
-
พจนานุกรมว่างเปล่าถูกสร้างขึ้น
-
องค์ประกอบของรายการซ้ำแล้วซ้ำอีก
-
รายการในพจนานุกรมมีการทำซ้ำมากกว่า
-
หากมีคีย์อยู่ในพจนานุกรม ค่าสูงสุดของคีย์และค่าจะถูกกำหนดให้กับผลลัพธ์
-
มิฉะนั้น ค่าจะถูกวางไว้ในผลลัพธ์
-
นี่คือผลลัพธ์ที่แสดงบนคอนโซล