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

如何用Python对文本文件数据升序排序?排序异常排查

排序结果异常:"Love 7"位置错误的解决方法

你的代码出现问题的核心原因是将分数以字符串类型存储并比较,而非数值类型。字符串比较是按字典序(字符ASCII码)进行的,比如字符串"7"的首字符'7'(ASCII码55)比"45"的首字符'4'(ASCII码52)大,所以"7"会被判定为比"45"大,导致"Love 7"错误地排在了"USA 45"前面。

修复方案1:修改原代码的类型转换

只需要在存储分数时,将字符串转为整数即可:

def sort_outputFiles():
    print('********* Sorting now **************')
    my_file = open("TextFile.txt", "r",encoding='utf-8')
    data = my_file.read()
    data_into_list = data.split("\n")
    my_file.close()
    score=[]
    links=[]
    for d in data_into_list:
        if d != '':
            s=d.split(',')
            # 这里把字符串转为整数
            score.append(int(s[0]))
            links.append(s[1])
    n = len(score)
    for i in range(n):
        for j in range(0, n-i-1):
            if score[j] < score[j+1]:
                score[j], score[j+1] = score[j+1], score[j]
                links[j], links[j+1] = links[j+1], links[j]

    for l,s in zip(links,score):
        print(l," ",s)

修复方案2:用Python内置sorted函数优化代码

手动实现冒泡排序不仅容易出错,效率也较低,推荐使用Python内置的排序工具,逻辑更简洁可靠:

def sort_outputFiles():
    print('********* Sorting now **************')
    # with语句自动管理文件,无需手动close
    with open("TextFile.txt", "r", encoding='utf-8') as my_file:
        # 过滤空行并去除每行首尾空白
        valid_lines = [line.strip() for line in my_file if line.strip()]
    
    # 按分数数值降序排序,key参数指定排序依据为转换后的整数
    sorted_data = sorted(
        (line.split(',') for line in valid_lines),
        key=lambda item: int(item[0]),
        reverse=True
    )
    
    # 遍历输出结果
    for num_str, text in sorted_data:
        print(text, " ", num_str)

运行上述任一修复后的代码,都能得到符合预期的输出,"Love 7"会正确排在最后一行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:40:38