在一个list列表中的多个dict字典按照键值对key-value来进行排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010870545/article/details/48185697
# -*- coding: utf-8 -*-
#主题:在一个list列表中的多个dict字典按照键值对key-value来进行排序
items = [
    {'name':'李四','age':40},
    {'name':'张三','age':30},
    {'name':'王五','age':50},
]
items0 = items[:]
# list.sort()或者sorted()中的参数key接收1个function(e.g.foo)
# apply to each element(e) of the list and sort element by the returned-value of 'foo(e)'
# which reminds of me the fucntion 'map()'?
foo = lambda s:s['age']
# 方法1:对原始的列表排序,改变原来的列表
items.sort(key=foo)
# 方法2:原始的列表作为参数传递给sorted(), 返回一个全新的按规则排序的列表,不改变原始的列表
items1 = sorted(items0, key=foo)

猜你喜欢

转载自blog.csdn.net/u010870545/article/details/48185697