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

如何对嵌套列表先按值降序排序,值相等时按字符串内数字升序排序?

Python嵌套列表自定义排序实现

问题场景

给定嵌套列表:

a = [["Test 1", 5],["Test 2", 3],["Test 3", 1], ["Test 4",3]]

需要按以下规则排序:

  • 优先按子列表的数值(索引1)降序排列(数值高的在前)
  • 当数值相同时,按字符串(索引0)中包含的数字升序排列(数字小的在前)

解决方案

使用Python内置的sorted()函数,通过自定义排序键实现需求:

a = [["Test 1", 5],["Test 2", 3],["Test 3", 1], ["Test 4",3]]

# 自定义排序规则
sorted_list = sorted(a, key=lambda item: (-item[1], int(''.join(filter(str.isdigit, item[0])))))

print(sorted_list)

代码说明

  1. 数值降序处理:-item[1]将数值取反,利用sorted()默认的升序特性,实现原数值的降序排列(大数值的负数更小,会排在前面)
  2. 字符串数字升序处理:int(''.join(filter(str.isdigit, item[0])))从字符串中提取所有数字字符,拼接后转换为整数,以此作为次排序键,实现数字的升序排列

运行结果

[["Test 1", 5], ["Test 2", 3], ["Test 4", 3], ["Test 3", 1]]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 20:30:45