Python如何对嵌套列表排序去重 筛选各类型Top3车辆生成新列表
问题原因
你之前的代码直接对全量记录排序取前3,没有先做「同类型车辆仅保留末尾值最大记录」的去重操作,所以会出现同类型车辆重复出现在结果里的问题。
正确实现步骤
- 先遍历全量车辆数据,按车辆类型做分组,每个类型下只保留末尾数值最大的单条记录
- 对去重后的所有记录,按末尾数值转整数后降序排序
- 截取排序结果的前3条,即为符合要求的结果
可直接运行的代码
vehicle_list = [['car', '123464', '4322445'], ['car', '64346', '643267'], ['bicycle', '1357', '78543'], ['bicycle', '75325', '75425'], ['car', '8652', '652466'], ['taxi', '653367', '63226'], ['taxi', '96544', '22267'], ['taxi', '86542222', '54433'], ['motorcycle', '675422', '56312'], ['motorcycle', '53225', '88885'], ['motorcycle', '773345', '9977'], ['motorcycle', '3466', '987444'], ['truck', '2455554', '5225544'], ['truck', '2455554', '344543'], ['train', '6543355', '6336']] # 按车辆类型存储对应最大末尾值的记录 type_best = {} for record in vehicle_list: v_type = record[0] current_tail = int(record[-1]) # 类型未录入,或者当前记录末尾值比已存的更大,就替换 if v_type not in type_best or current_tail > int(type_best[v_type][-1]): type_best[v_type] = record # 排序后取前三 top_vehicle = sorted(type_best.values(), key=lambda x: int(x[-1]), reverse=True)[:3] print(top_vehicle)
运行输出
[['truck', '2455554', '5225544'], ['car', '123464', '4322445'], ['motorcycle', '3466', '987444']]
完全匹配预期结果。
内容的提问来源于stack exchange,提问作者user19239587
相关产品推荐
相关产品推荐

