对水果价格进行排序
当列表中的元素是字典时,使用sort()方法进行排序,需要指定key属性,通过它来实现按指定字段排序。
下面代码实现了按水果价格从高到底排序
list_dict = [{'name': '苹果', 'price': 9.9},
{'name': '香蕉', 'price': 5.9},
{'name': '圣女果', 'price': 7.45}]
print("列表排序之前:")
for item in list_dict:
print(item)
print("列表排序之后:")
list_dict.sort(key=lambda x: x['price'], reverse=True)
for item in list_dict:
print(item)
运行结果:
列表排序之前:
{'name': '苹果', 'price': 9.9}
{'name': '香蕉', 'price': 5.9}
{'name': '圣女果', 'price': 7.45}
列表排序之后:
{'name': '苹果', 'price': 9.9}
{'name': '圣女果', 'price': 7.45}
{'name': '香蕉', 'price': 5.9}