Python – 按键的第 i 个索引值对字典列表进行排序
pythonserver side programmingprogramming更新于 2025/10/23 3:24:17
当需要根据按键的第 ‘i’索引值对字典列表进行排序时,使用 ‘sorted’ 方法和 lambda 方法。
示例
下面是相同的演示 −
my_list = [{"Python" : "Best", "to" : "Code"},
{"Python" : "Good", "to" : "Learn"},
{"Python" : "object", "to" : "cool"},
{"Python" : "oriented", "to" : "language"}]
print("列表为: " )
print(my_list)
K = "Python"
print("K 的值为 ")
print(K)
i = 2
print("i 的值为 :")
print(i)
my_result = sorted(my_list, key = lambda sub: sub[K][i])
print("结果列表是:")
print(my_result)
输出
列表为:
[{'Python': 'Best', 'to': 'Code'}, {'Python': 'Good', 'to': 'Learn'}, {'Python': 'object', 'to': 'cool'},
{'Python': 'oriented', 'to': 'language'}]
K 的值为
Python
i 的值为 :
2
结果列表为:
[{'Python': 'iented', 'to': 'language'}, {'Python': 'object', 'to': 'cool'}, {'Python': 'Good', 'to':
'Learn'}, {'Python': 'Best', 'to': 'Code'}]
解释
创建字典列表并显示在控制台。
定义 'K' 的值并显示在控制台上。
定义 'i' 的值并显示在控制台上。
使用 'sorted' 方法以 lambda 函数为键对列表进行排序。
这被分配给一个变量。
此变量显示为控制台上的输出。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

