เมื่อจำเป็นต้องเรียงลำดับรายการพจนานุกรมตามค่าดัชนี 'i'th ของคีย์ ระบบจะใช้เมธอด 'sorted' และวิธีการแลมบ์ดา
ตัวอย่าง
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
my_list = [{"Python" : "Best", "to" : "Code"},
{"Python" : "Good", "to" : "Learn"},
{"Python" : "object", "to" : "cool"},
{"Python" : "oriented", "to" : "language"}]
print("The list is : " )
print(my_list)
K = "Python"
print("The value of K is ")
print(K)
i = 2
print("The value of i is :")
print(i)
my_result = sorted(my_list, key = lambda sub: sub[K][i])
print("The resultant list is : ")
print(my_result) ผลลัพธ์
The list is :
[{'Python': 'Best', 'to': 'Code'}, {'Python': 'Good', 'to': 'Learn'}, {'Python': 'object', 'to': 'cool'},
{'Python': 'oriented', 'to': 'language'}]
The value of K is
Python
The value of i is :
2
The resultant list is :
[{'Python': 'oriented', 'to': 'language'}, {'Python': 'object', 'to': 'cool'}, {'Python': 'Good', 'to':
'Learn'}, {'Python': 'Best', 'to': 'Code'}] คำอธิบาย
-
รายการพจนานุกรมถูกสร้างขึ้นและแสดงบนคอนโซล
-
ค่าของ 'K' ถูกกำหนดและแสดงบนคอนโซล
-
ค่าของ 'i' ถูกกำหนดและแสดงบนคอนโซล
-
วิธี 'sorted' ใช้เพื่อจัดเรียงรายการโดยใช้ฟังก์ชัน lambda เป็นคีย์
-
สิ่งนี้ถูกกำหนดให้กับตัวแปร
-
ตัวแปรนี้แสดงเป็นเอาต์พุตบนคอนโซล