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 函式作為鍵。

  • 將其賦值給一個變數。

  • 此變數顯示為控制檯上的輸出。

更新於: 13-9 月-2021

382 次瀏覽

開啟您的事業

完成該課程即可獲得認證

開始
廣告
© . All rights reserved.