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

使用Python对包含字符串和数字的txt文件按数值升序排序

Python实现按行末数值排序TXT文件的方法

直接上可运行的代码,假设你的源文件名为input.txt,排序后结果输出到output.txt:

# 读取文件内容,过滤空行
with open("input.txt", "r", encoding="utf-8") as f:
    content = [line.rstrip("\n") for line in f if line.strip()]

# 按每行末尾的数值升序排序
sorted_content = sorted(content, key=lambda line: int(line.split()[-1]))

# 输出结果到新文件
with open("output.txt", "w", encoding="utf-8") as f:
    f.write("\n".join(sorted_content))

# 如需直接打印排序结果,取消下面注释即可
# print("\n".join(sorted_content))

逻辑说明

  • 读取阶段自动过滤了空行,避免空行导致的拆分、转整数报错
  • 排序时用split()默认按任意空白符拆分每行,取最后一个元素转整数作为排序依据,不会出现字符串排序时"100" < "20"的错误
  • 如果你的数值不是在行末,调整split()后的索引即可,比如数值在第二列就把[-1]改成[1](索引从0开始)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 13:15:04