首页 > 解决方案 > 如何根据几个参数在python中对字典进行排序?

问题描述

我有四个具有相同键的单独字典,如下所示:

s = {'name': 'Spain', 'wins': 1, 'loses' : 1, 'draws': 1, 'goal, difference': 4, 'points': 4}
e = {'name': 'England', 'wins': 2, 'loses' : 1, 'draws': 0, 'goal difference': 1, 'points': 6}
p = {'name': 'Portugal', 'wins': 0, 'loses' : 1, 'draws': 2, 'goal difference': 0, 'points': 2}
g = {'name': 'Germany', 'wins': 1, 'loses' : 1, 'draws': 1, 'goal difference': 5, 'points': 4}

目标是根据“点”对它们进行排序,如果相等,则必须根据字母名称对其进行排序,如下所示:

'England' 'wins': 2 'loses' : 1 'draws': 0 'goal difference': 1 'points': 6
'Germany' 'wins': 1 'loses' : 1 'draws': 1 'goal difference': 5 'points': 4
'Spain' 'wins': 1 'loses' : 1 'draws': 1 'goal, difference': 4 'points': 4
'Portugal' 'wins': 0 'loses' : 1 'draws': 2 'goal difference': 0 'points': 2

任何想法都会很棒。

标签: pythonsortingdictionary

解决方案


您可以将key参数传递给 Python 标准库sortsorted函数以自定义排序。在您的情况下,它将是:

custom_order = sorted([s, e, p, g], key=lambda d: (-d['points'], d['name']))

解释:在我们的例子中,排序比较了负点计数和名称的动态创建的元组。元组按第一个元素进行比较,如果它们相等,则按第二个等。因此,您的字典将按点进行比较,如果点相等,则按名称进行比较,如您所愿。这些点是负数以实现点的降序,但保持名称的升序。


推荐阅读