按x然后按y对字典列表进行排序 [英] sort a list of dicts by x then by y

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

问题描述

我想对这些信息(名称,点和时间)进行排序:

I want to sort this info(name, points, and time):

list = [
    {'name':'JOHN', 'points' : 30, 'time' : '0:02:2'},
    {'name':'KARL','points':50,'time': '0:03:00'}
]

所以,我想要的是该列表首先按得分排序,然后按游戏时间排序(在我的示例中,由于他的时间少,所以亚光先走了.有什么帮助吗?

so, what I want is the list sorted first by points made, then by time played (in my example, matt go first because of his less time. any help?

我正在尝试:

import operator
list.sort(key=operator.itemgetter('points', 'time'))

但得到了TypeError: list indices must be integers, not str.

推荐答案

您的示例对我有用.我建议您不要使用list作为变量名,因为它是内置类型.

Your example works for me. I would advise you not to use list as a variable name, since it is a builtin type.

您也可以尝试执行以下操作:

You could try doing something like this also:

list.sort(key=lambda item: (item['points'], item['time']))

这篇关于按x然后按y对字典列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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