使用 lambda 函数在 Python 中按值对字典列表进行排序的方法
当需要根据值对字典列表进行排序时,可以使用lambda函数。
以下是相同的演示-
示例
from operator import itemgetter my_list = [{ "name" : "Will", "age" : 56}, { "name" : "Rob", "age" : 20 }, { "name" : "Mark" , "age" : 34 }, { "name" : "John" , "age" : 24 }] print("按年龄排序的列表是: ") print(sorted(my_list, key=lambda i: i['age'])) print("按年龄和姓名排序的列表是: ") print(sorted(my_list, key=lambda i: (i['age'], i['name']))) print("按年龄降序排列的列表是: ") print(sorted(my_list, key=lambda i: i['age'],reverse=True))输出结果
按年龄排序的列表是: [{'name': 'Rob', 'age': 20}, {'name': 'John', 'age': 24}, {'name': 'Mark', 'age': 34}, {'name': 'Will', 'age': 56}] 按年龄和姓名排序的列表是: [{'name': 'Rob', 'age': 20}, {'name': 'John', 'age': 24}, {'name': 'Mark', 'age': 34}, {'name': 'Will', 'age': 56}] 按年龄降序排列的列表是: [{'name': 'Will', 'age': 56}, {'name': 'Mark', 'age': 34}, {'name': 'John', 'age': 24}, {'name': 'Rob', 'age': 20}]
解释
字典元素列表已定义并显示在控制台上。
使用sorted方法,并将键指定为'lambda'。
字典列表再次使用lambda作为两个参数进行排序。
输出显示在控制台上。