You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

通过中间字典用一个列表排序另一个列表时元素丢失问题排查

按身高排序姓名列表出错的原因及解决办法

问题背景

现有两组数据:

names = ["Alice", "Bob", "Bob"]
heights = [155, 185, 150]

其中names[i]对应heights[i],需求是按身高从高到低排序names,预期输出为["Bob", "Alice", "Bob"]。

你编写的代码如下:

temp = dict(zip(names, heights))
sort_temp = sorted(temp.items(), key=lambda x:x[1], reverse=True)
res = []
for i in sort_temp:
    res.append(i[0])
print(res)

实际运行结果却为["Alice", "Bob"],和预期不符。

错误原因

核心问题出在字典的键唯一性:
当你用dict(zip(names, heights))创建字典时,字典的键不允许重复。原列表里有两个"Bob",第二个"Bob"会覆盖第一个"Bob"对应的键值对,最终字典里只保留{"Alice": 155, "Bob": 150}这两组数据,后续排序自然只能得到两个元素的结果。

修正方案

方案一:直接对元组列表排序

避免使用字典,直接将姓名和身高打包成元组列表(不会去重),再按身高排序:

names = ["Alice", "Bob", "Bob"]
heights = [155, 185, 150]

# 打包为元组列表,保留所有数据
temp = list(zip(names, heights))
# 按身高倒序排序
sorted_temp = sorted(temp, key=lambda x: x[1], reverse=True)
# 提取排序后的姓名
res = [item[0] for item in sorted_temp]
print(res)  # 输出:['Bob', 'Alice', 'Bob']

方案二:通过索引排序

先获取按身高倒序排列的索引,再根据索引提取对应姓名:

names = ["Alice", "Bob", "Bob"]
heights = [155, 185, 150]

# 获取按身高倒序排列的索引列表
sorted_indices = sorted(range(len(heights)), key=lambda i: heights[i], reverse=True)
# 根据索引提取姓名
res = [names[i] for i in sorted_indices]
print(res)  # 输出:['Bob', 'Alice', 'Bob']

内容的提问来源于stack exchange,提问作者Sophia

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 16:40:39