按两个键对字典列表进行排序

anv*_*nvd 5 python dictionary list python-2.7

我有这个字典列表:

[{'score': '1.9', 'id': 756, 'factors': [1.25, 2.25, 2.5, 2.0, 1.75]}, {'score': '2.0', 'id': 686, 'factors': [2.0, 2.25, 2.75, 1.5, 2.25]}, {'score': '2.0', 'id': 55, 'factors': [1.5, 3.0, 2.5, 1.5, 1.5]}, {'score': '1.9', 'id': 863, 'factors': [1.5, 3.0, 1.5, 2.5, 1.5]}]
Run Code Online (Sandbox Code Playgroud)

我可以按分数排序 : sorted(l, key=lambda k: k['score'], reverse=True)。但是我已经打平了分数。如何先按分数排序,然后按 id asc 或 desc 排序?

Nic*_*ick 9

您可以按元组排序:

sorted(l, key=lambda k: (float(k['score']), k['id']), reverse=True)
Run Code Online (Sandbox Code Playgroud)

这将按score降序排序,然后id降序。请注意,由于score是字符串值,因此需要将其转换为float进行比较。

[
 {'score': '2.0', 'id': 686, 'factors': [2.0, 2.25, 2.75, 1.5, 2.25]},
 {'score': '2.0', 'id': 55, 'factors': [1.5, 3.0, 2.5, 1.5, 1.5]},
 {'score': '1.9', 'id': 863, 'factors': [1.5, 3.0, 1.5, 2.5, 1.5]},
 {'score': '1.9', 'id': 756, 'factors': [1.25, 2.25, 2.5, 2.0, 1.75]}
]
Run Code Online (Sandbox Code Playgroud)

要按id升序排序,请使用-k['id'](对负数进行降序排序相当于对非负数进行升序排序):

sorted(l, key=lambda k: (float(k['score']), -k['id']), reverse=True)

[
 {'score': '2.0', 'id': 55, 'factors': [1.5, 3.0, 2.5, 1.5, 1.5]},
 {'score': '2.0', 'id': 686, 'factors': [2.0, 2.25, 2.75, 1.5, 2.25]},
 {'score': '1.9', 'id': 756, 'factors': [1.25, 2.25, 2.5, 2.0, 1.75]},
 {'score': '1.9', 'id': 863, 'factors': [1.5, 3.0, 1.5, 2.5, 1.5]}
]
Run Code Online (Sandbox Code Playgroud)