python - 使用多个键对字典列表进行排序
问题描述
我在列表中有字典列表,需要按点键对列表进行排序。
我能够使用“点”列表的第一个位置进行排序,但想根据第一个位置和第二个位置进行排序。
a = [
{
'label':'a',
'points': [[70,2],[60,4]]
}
,
{
'label':'b',
'points': [[90,6],[80,8]]
}
,
{
'label':'c',
'points': [[50,10],[40,12]]
}
]
def sort_point_by_first_occur(item):
print item['points'][0][0]
return item['points'][0][0]
print sorted(a, key=sort_point_by_first_occur)
电流输出:-
[{'points': [[50, 10], [60, 4]], 'label': 'a'}, {'points': [[50, 2], [40, 12]], 'label': 'c'}, {'points': [[90, 6], [80, 8]], 'label': 'b'}]
异常输出:
[{'points': [[50, 2], [60, 4]], 'label': 'a'}, {'points': [[50, 10], [40, 12]], 'label': 'c'}, {'points': [[90, 6], [80, 8]], 'label': 'b'}]
解决方案
我建议加权到 2 个值
def sort_point_by_first_occur(item):
weighted = item['points'][0][0]*1000 + item['points'][0][1]
return weighted
这样,如果第一个位置相同,则第二个位置将是决胜局
推荐阅读
- sql - DML 中的自动递增逻辑
- swift - 为测试目标/单元测试文件禁用一些 SwiftLint 规则
- sql - 如何使用谷歌图表(饼图)将 jsonresult 数据显示为图表视图而不是 asp.net mvc 中的数组
- google-apps-script - 使用 AppsScript 从 Google 表格插入链接图表
- gatsby - Gatsby CMS - Failed to load settings from /.netlify/identity
- java - 如何在有向图Java中打印每个循环?
- ios - UISplitViewController 在细节上滑动来回导航
- php - 在另一个函数中调用控制器的索引函数
- vba - Excel For Each ws 不会进入下一个 ws
- appium - 测试将 Appium 脚本上传到 MS App Center 所需的更改