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

如何将包含用户名称、金额的数组按金额降序排序生成排行榜?

修复方案

核心是使用Python内置的sorted()函数对原始数据按money字段降序排序,同时修正原有代码的逻辑瑕疵。

修正后代码

@client.command()
async def score(ctx):
    channel = ctx.message.channel
    data = loadjson()
    # 按用户金额降序排序所有数据
    sorted_data = sorted(data, key=lambda item: item["money"], reverse=True)
    scoreboard = []
    
    for line in sorted_data:
        current_name = line["name"]
        current_money = line["money"]
        value = f"{current_name} {current_money}"
        scoreboard.append(value)
    
    # 仅当无有效数据时插入空提示
    if not scoreboard:
        scoreboard.append("Empty!")
    
    # 若需要发送到Discord频道,替换为以下代码即可
    # await ctx.send("\n".join(scoreboard))
    print(scoreboard)

修改说明

  • 排序实现:通过sorted()的key参数指定以money字段为排序依据,reverse=True开启降序排列,直接得到按金额从高到低排序的用户列表
  • 逻辑优化:
    • 移除了原代码中Minimum_money阈值判断,避免遗漏金额≤0的用户数据
    • 空列表判断移到遍历结束后执行,规避了循环过程中错误插入空提示的问题
    • 改用f-string拼接字符串,代码可读性更高

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 01:09:03