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

不使用pandas按scores字段排序CSV列实现排行榜的方法

问题根因

原代码无法输出降序排行榜的核心问题有3个:

  • 读取CSV时将分数字段存储为字符串类型,直接排序会按字典序而非数值大小比对,导致排序结果错误
  • 未对玩家字典数据按分数字段做排序处理,直接遍历字典无法得到有序输出
  • 代码存在缩进错误:leaderboard函数被错误缩进在loadData函数内部,外部无法正常调用;同时用line[0:-1]去除换行的写法兼容性差,会切掉无换行尾行的最后一个有效字符
修正实现方案

无需引入pandas等第三方库,仅需调整数据类型、修正缩进、增加排序逻辑即可,完整可运行代码如下:

def loadData():
    player = {}
    # 用with上下文管理文件,自动处理文件关闭,避免资源泄漏
    with open('Leaderboard.csv', 'r', encoding='utf-8') as fileHandle:
        for line in fileHandle:
            # 去除首尾换行、空白字符,跳过空行
            line = line.strip()
            if not line:
                continue
            data = line.split(",")
            playerName = data[0]
            # 分数转为整数类型,用于数值大小排序
            playerScore = int(data[1])
            playerPattern = data[2]
            playerData = {
                "Score": playerScore,
                "Pattern": playerPattern
            }
            player[playerName] = playerData
    return player

# 修正缩进,顶格定义为全局函数
def leaderboard(player):
    print("=========================================")
    print("              LEADERBOARD")
    # 对玩家数据按分数做降序排序
    sorted_players = sorted(
        player.items(),
        key=lambda item: item[1]["Score"],
        reverse=True
    )
    for playerName, playerData in sorted_players:
        playerScore = playerData["Score"]
        playerPattern = playerData["Pattern"]
        print(f"{playerName} - {playerScore} - {playerPattern}")
    print("\n")

if __name__ == "__main__":
    player = loadData()
    leaderboard(player)
运行输出效果

使用提供的示例CSV运行后,会输出符合预期的降序排行榜:

=========================================
              LEADERBOARD
John - 55 - okelf
Gian - 40 - jfue
Eman - 30 - kerf
Hans - 10 - ie

逻辑说明:

  • 内置sorted函数为Python原生实现,无需依赖第三方库,key参数指定取玩家数据中的Score字段作为排序依据,reverse=True表示从高到低降序排列
  • 分数字段提前转为int类型,避免字符串排序的字典序错误(比如字符串"100"会排在"20"前面的异常问题)
  • 增加空行跳过逻辑,避免CSV中存在空行时触发索引报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 22:51:19