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

为何仅修改一个符号的两段Python代码输出结果不同?

为什么两段仅排序key不同的Python代码输出结果不一致?

两段Python代码仅在sort方法的key参数上有差异:第一段用x[3]作为排序依据,第二段用x[-1]。原本预期输出一致,但实际结果不同,原因是什么?

第一段代码

def get_total_score(data):
    data_with_result_score = list(map(lambda x: (*x, x[1] + x[2] + x[3]), data))
    data_with_result_score.sort(key=lambda x: x[3])
    return data_with_result_score

data = [
    ('Amanda', 37, 78, 67),
    ('Patricia', 78, 93, 68),
    ('Marcos', 79, 67, 89),
    ('Dmitry', 67, 68, 100),
    ('Andrey', 100, 78, 76),
    ('Victoria', 93, 69, 96),
]
print(get_total_score(data))
# [('Amanda', 37, 78, 67, 182), ('Patricia', 78, 93, 68, 239), ('Andrey', 100, 78, 76, 254), ('Marcos', 79, 67, 89, 235), ('Victoria', 93, 69, 96, 258), ('Dmitry', 67, 68, 100, 235)]

第二段代码

def get_total_score(data):
    data_with_result_score = list(map(lambda x: (*x, x[1] + x[2] + x[3]), data))
    data_with_result_score.sort(key=lambda x: x[-1]) #The difference in x[]
    return data_with_result_score

data = [
    ('Amanda', 37, 78, 67),
    ('Patricia', 78, 93, 68),
    ('Marcos', 79, 67, 89),
    ('Dmitry', 67, 68, 100),
    ('Andrey', 100, 78, 76),
    ('Victoria', 93, 69, 96),
]
print(get_total_score(data))
# [('Amanda', 37, 78, 67, 182), ('Marcos', 79, 67, 89, 235), ('Dmitry', 67, 68, 100, 235), ('Patricia', 78, 93, 68, 239), ('Andrey', 100, 78, 76, 254), ('Victoria', 93, 69, 96, 258)]

原因分析

核心问题是**map处理后,每个元素的结构发生了变化**:

  • 原数据的每个元素是4元组,格式为(姓名, 分数1, 分数2, 分数3)
  • 经过map(lambda x: (*x, x[1]+x[2]+x[3]), data)处理后,每个元素变成了5元组,新增的第5个元素是三个分数的总和,格式为(姓名, 分数1, 分数2, 分数3, 总分)

此时:

  • x[3]指向的是原4元组的第4个元素,也就是原数据里的第三个分数(比如Amanda的67,Dmitry的100)
  • x[-1]指向的是新增的第5个元素,也就是三个分数的总和(比如Amanda的182,Marcos的235)

两个排序依据完全不同,自然输出结果不一样:

  • 第一段代码按「第三个分数」从小到大排序,所以顺序是Amanda(67)→Patricia(68)→Andrey(76)→Marcos(89)→Victoria(96)→Dmitry(100)
  • 第二段代码按「总分」从小到大排序,所以顺序是Amanda(182)→Marcos(235)→Dmitry(235)→Patricia(239)→Andrey(254)→Victoria(258)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 10:05:35