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

Python 二维字符串列表按第二元素排序及获取最高值对应项咨询

修复方案

可直接运行的修正代码

sqrm_price= [['1999', '7951'], ['2000', '8868'], ['2001', '12502']] 

def highPrice(sqrm_price):
    # 排序时将价格转为整数作为排序依据
    sort_price = sorted(sqrm_price, key = lambda x: int(x[1]), reverse=True)
    # 从排序后的首条记录中分别取年份和价格
    print(f"The year {sort_price[0][0]} has the highest price with {sort_price[0][1]}$")      

highPrice(sqrm_price) 

原代码问题说明

  • 排序规则错误:原代码直接使用字符串类型的价格排序,字符串按字符逐一对比,会出现"12502" < "8868"的错误结果,转为整数类型后可按数值大小正确排序。
  • 输出取值错误:原代码直接取原列表末尾元素作为年份不符合逻辑,且排序返回的每个元素是包含年份和价格的子列表,不能直接和字符串拼接,需要按索引取对应字段。

更高效的优化方案

如果仅需要找最高价格对应条目,不需要全量排序,可以用max函数直接查找,时间复杂度更低:

def highPrice(sqrm_price):
    highest_item = max(sqrm_price, key=lambda x: int(x[1]))
    print(f"The year {highest_item[0]} has the highest price with {highest_item[1]}$")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:06:03