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