基于ImageDetails的count属性获取Top5应用名称的技术需求
问题与解决方案
问题描述
给定API返回的结构化数据如下:
data = {"ImageDetails": [ {"application": "unknownApp", "count": 107757}, {"application": "app6", "count": 1900}, {"application": "app8", "count": 0}, {"application": "app3", "count": 100}, {"application": "app9", "count": 0}, {"application": "app1", "count": 0}, {"application": "app10", "count": 0}, {"application": "app7", "count": 0} ]}
需基于ImageDetails中每个对象的count属性降序排序,提取排名前5的应用名称,预期输出为:['unknownApp', 'app6', 'app3', 'app8', 'app9']
实现步骤
- 从数据中提取
ImageDetails列表 - 按
count字段降序排序,当多个应用count值相同时,保留其在原列表中的相对顺序(稳定排序) - 截取排序后的前5个元素,提取每个元素的
application字段值组成结果列表
代码示例
# 提取ImageDetails列表 image_details = data["ImageDetails"] # 按count降序排序,count相同时维持原顺序 sorted_details = sorted(image_details, key=lambda x: (-x["count"], image_details.index(x))) # 提取前5个应用名称 top5_apps = [item["application"] for item in sorted_details[:5]] print(top5_apps) # 输出结果:['unknownApp', 'app6', 'app3', 'app8', 'app9']
内容的提问来源于stack exchange,提问作者anonymous
相关产品推荐
相关产品推荐

