Python——按鍵的第 i 個索引值對字典列表進行排序
當需要根據鍵的“i”索引值對字典列表進行排序時,可以使用“sorted”方法和 lambda 方法。
示例
以下是對此進行演示的示例 -
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 函式作為鍵。
將其賦值給一個變數。
此變數顯示為控制檯上的輸出。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP