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

Python实现城镇与销售额双列表排序的返回值修正

任务要求
  • 实现函数接收两个列表入参:lst1 为城镇名称列表,lst2 为对应城镇的销售额列表
  • 返回两个列表的副本,遵循以下排序规则:
    • 优先按销售额降序排列,城镇名称与对应销售额保持一一绑定
    • 若多个城镇销售额相同,则按照城镇名称A-Z升序排列
现有实现的偏差

已编写的代码如下:

def sort_lists(lst1, lst2):
    tuples_list = list(zip(lst1, lst2))
    sorted_list = sorted(tuples_list, key = lambda x:(-x[1], x[0]))
    unzipped_list = zip(*sorted_list)
    return (list(unzipped_list))

测试调用样例:

print(list_sorting(['Eugene', 'Phoenix', 'Peoria', 'Ashwood', 'Buxton', 'Crawley', 'Parkdale'], 
[45,23,21,14,8,12,23]))
  • 判题系统期望的输出:
(['Eugene', 'Parkdale', 'Phoenix', 'Peoria', 'Ashwood', 'Crawley', 'Buxton'], [45, 23, 23, 21, 14, 12, 8])
  • 当前代码实际输出:
[('Eugene', 'Parkdale', 'Phoenix', 'Peoria', 'Ashwood', 'Crawley', 'Buxton'), (45, 23, 23, 21, 14, 12, 8)]

当前实现的排序逻辑完全符合要求,偏差仅在返回值结构上:

  1. 解包得到的城镇名、销售额序列是元组类型,不符合返回列表的要求
  2. 外层返回结构是列表,不符合“两个列表组成元组返回”的格式要求
修正方案

无需调整原有排序逻辑,仅修正解包后的类型转换与返回结构即可。修正后代码:

def sort_lists(lst1, lst2):
    tuples_list = list(zip(lst1, lst2))
    sorted_list = sorted(tuples_list, key = lambda x:(-x[1], x[0]))
    # 分别提取排序后的城镇名、销售额,生成对应列表
    sorted_towns = [item[0] for item in sorted_list]
    sorted_sales = [item[1] for item in sorted_list]
    # 用元组包裹两个列表返回,匹配输出结构要求
    return (sorted_towns, sorted_sales)

该修改完全保留原有排序规则,不会影响后续其他依赖该函数的测试场景的排序结果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.23 22:36:02