python - 如何根据几个参数在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
任何想法都会很棒。
解决方案
您可以将key
参数传递给 Python 标准库sort
或sorted
函数以自定义排序。在您的情况下,它将是:
custom_order = sorted([s, e, p, g], key=lambda d: (-d['points'], d['name']))
解释:在我们的例子中,排序比较了负点计数和名称的动态创建的元组。元组按第一个元素进行比较,如果它们相等,则按第二个等。因此,您的字典将按点进行比较,如果点相等,则按名称进行比较,如您所愿。这些点是负数以实现点的降序,但保持名称的升序。
推荐阅读
- django - 在 Django/Vue 应用程序中更改公共 index.html 中的 chunk_vendors/app js 文件导入 url
- laravel - 使用一些数据过滤从日期到日期
- javascript - 如何使用 Javascript 随机化 WordPress 中的图像(高级自定义字段)
- f# - 为什么在这种情况下在 F# 中使用引用
- swift - 如何在类内设置计算值的绑定(SwiftUI)
- pyspark - 使用 pyspark 联合 Delta Lake 表
- javascript - 自动滚动到自动完成中的特定选项
- python - 即使我在运行代码后有一个结束条件,我的循环也会无休止地运行
- python - x.reshape([1,28,28,1]) 重塑意义
- api - BigCommerce 通过电子邮件收到的密码重置链接需要通过 Headless App 用于通过 API 调用重置密码吗?