Python:如何按几个值对字典列表进行排序? [英] Python: How to sort a list of dictionaries by several values?

查看:227
本文介绍了Python:如何按几个值对字典列表进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想首先按一个值对列表进行排序,然后按第二个值对列表进行排序.是否有捷径可寻?这是一个小例子:

I want to sort a list at first by a value and then by a second value. Is there an easy way to do this? Here is a small example:

A = [{'name':'john','age':45},
     {'name':'andi','age':23},
     {'name':'john','age':22},
     {'name':'paul','age':35},
     {'name':'john','age':21}]

此命令用于按'name'对该列表进行排序:

This command is for sorting this list by 'name':

sorted(A, key = lambda user: user['name'])

但是我如何用第二个值对列表进行排序?就像本例中的'age'.

But how I can sort this list by a second value? Like 'age' in this example.

我想要这样的排序(首先按'name'排序,然后按'age'排序):

I want a sorting like this (first sort by 'name' and then sort by 'age'):

andi - 23
john - 21
john - 22
john - 45
paul - 35

谢谢!

推荐答案

>>> A = [{'name':'john','age':45},
     {'name':'andi','age':23},
     {'name':'john','age':22},
     {'name':'paul','age':35},
     {'name':'john','age':21}]
>>> sorted(A, key = lambda user: (user['name'], user['age']))
[{'age': 23, 'name': 'andi'}, {'age': 21, 'name': 'john'}, {'age': 22, 'name': 'john'}, {'age': 45, 'name': 'john'}, {'age': 35, 'name': 'paul'}]

这按两个属性的元组排序,以下是等效的,并且更快/更干净:

This sorts by a tuple of the two attributes, the following is equivalent and much faster/cleaner:

>>> from operator import itemgetter
>>> sorted(A, key=itemgetter('name', 'age'))
[{'age': 23, 'name': 'andi'}, {'age': 21, 'name': 'john'}, {'age': 22, 'name': 'john'}, {'age': 45, 'name': 'john'}, {'age': 35, 'name': 'paul'}]

来自评论:@Bakuriu

From the comments: @Bakuriu

我敢保证两者之间没有太大区别,但是itemgetter避免了一些开销,因为它在调用CALL_FUNCTION)中生成了tuple >将必须调用该函数,加载各种常量(其他字节码),最后调用下标(BINARY_SUBSCR),构建tuple并将其返回...对于解释器而言,这还有很多工作要做.

I bet there is not a big difference between the two, but itemgetter avoids a bit of overhead because it extracts the keys and make the tuple during a single opcode(CALL_FUNCTION), while calling the lambda will have to call the function, load the various constants(which are other bytecodes) finally call the subscript (BINARY_SUBSCR), build the tuple and return it... that's a lot more work for the interpreter.

总结:itemgetter将执行完全保持在C级别,因此它要尽可能快.

To summarize: itemgetter keeps the execution fully on the C level, so it's as fast as possible.

这篇关于Python:如何按几个值对字典列表进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆