python中字典列表的两级排序

2024-04-27 04:41:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一份字典清单如下:

 {"id": 1, "score": some_score.. othe values}
 {"id": 1, "score": some_differetscore.. othe values}  
 {"id": 22, "score": some_score.. othe values}
 {"id": 3, "score": some_score.. othe values}

我希望得到的是以这样一种方式遍历这个列表,使其排序如下。在

列表按“id”排序,然后用“score”反向排序

所以所有带“id”1的条目都被组合在一起,然后得分最高的条目就在最前面了?? 我怎么做的?在

谢谢


Tags: id列表字典排序方式条目somescore
2条回答

实际上是相同的,但更清洁,单元可测试:

def weight(data):
    """We sort the data first by its ID, then by descending score."""
    return data["id"], -data["score"]

sorted(mylist, key=weight)

试试这个:

sorted(mylist, key=lambda d: (d["id"], -d["score"]))

相关问题 更多 >