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

如何按字符串列表中的intvalue值大小对列表进行排序?

按字符串中的整数字段排序列表

要实现按Name:intvalue:othervalue格式字符串里的intvalue数值排序,直接用Python内置的sorted()函数(或列表的sort()方法),通过key参数指定排序依据即可,核心是提取并转换中间的整数字段:

核心思路

  • 用split(':')把每个字符串按冒号分割成三部分,取索引为1的元素(即intvalue部分)
  • 将提取到的字符串转为整数,确保按数值大小排序(若不转整数,会按字符串字典序排序,结果不符合预期)

代码示例

# 输入列表
input_list = ['gop:1245:random', 'random:35:eee', 'random3:100000:efa']

# 按intvalue升序排序,生成新列表
sorted_list = sorted(input_list, key=lambda x: int(x.split(':')[1]))

# 输出结果
print(sorted_list)
# 输出: ['random:35:eee', 'gop:1245:random', 'random3:100000:efa']

原地排序(修改原列表)

如果不需要保留原列表,直接用列表的sort()方法原地排序:

input_list = ['gop:1245:random', 'random:35:eee', 'random3:100000:efa']
input_list.sort(key=lambda x: int(x.split(':')[1]))
print(input_list)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 11:04:58