如何从 JSON 数据集中按降序返回前 3 个用户 ID 的列表

乘风 python 194

原文标题How to return a list of top 3 userIds in descending order from JSON dataset

[{“id”: 23456,”pieceId”: 25395616,”status”: 10800,”userId”: 911,”startTime”: 1490989764,”endTime”: 1491001113},{“id”: 333883698,”pieceId”: 25390812,”status”: 10451,”userId”: 88738562,”startTime”: 1491004450,”endTime”: 1491004579

原文链接:https://stackoverflow.com//questions/71508018/how-to-return-a-list-of-top-3-userids-in-descending-order-from-json-dataset

回复

我来回复
  • Nguyễn Lê Trọng Đạt的头像
    Nguyễn Lê Trọng Đạt 评论

    最简单的方法是使用自定义排序并从排序列表中获取子列表。

    key=lamda x:-x["userId"]是自定义排序功能。

    x前的减号表示删除“userId”属性。您可以在自定义Python列表排序中研究如何在python中自定义排序

    list.sort(key=lambda x: -x["userId"])
    result = list[0:3]
    

    如果您的数据类型是字符串,您可以在对列表进行排序之前使用它。

    import json
    list  = json.loads(stringData)
    
    2年前 0条评论