首页 > 解决方案 > 使用多个键对字典列表进行排序

问题描述

我在列表中有字典列表,需要按点键对列表进行排序。

我能够使用“点”列表的第一个位置进行排序,但想根据第一个位置和第二个位置进行排序。

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'}]

标签: python

解决方案


我建议加权到 2 个值

def sort_point_by_first_occur(item):
    weighted = item['points'][0][0]*1000 + item['points'][0][1]
    return weighted

这样,如果第一个位置相同,则第二个位置将是决胜局


推荐阅读