【问题标题】:Is there a way to make a leaderboard with several json files?有没有办法用几个 json 文件制作排行榜?
【发布时间】:2019-06-12 03:41:24
【问题描述】:

在我当前的命令中,我从一个名为 users.json 的单个 json 文件获取排行榜,该文件存储来自多个用户的多个 XP:

@bot.command(pass_context=True)
async def top(ctx):

    with open('profile/users.json', 'r') as fp:
        users = json.load(fp)
        lb = [(member, users[member.id].get('xp')) for member in ctx.message.server.members if member.id in users]
        lb.sort(key=lambda x: x[1], reverse=True)

但是,我更改了命令,并让每个人将他们的 XP 存储在单独的 json 文件中: 曾经的 'profile/users.json' 变成了几个 'profile/{}.json'.format(ctx.message.author.id)
现在在 profile 文件夹中,每个用户都有几个 json 文件,以及他们各自的 xp,而不是单个 json 文件。 我想要一种使用我的代码一次使用多个 json 文件而不是一个文件来创建排行榜的方法,我该怎么办?
请完整答案,如果您需要更多数据,请告诉我,我将编辑问题

【问题讨论】:

    标签: python json discord discord.py leaderboard


    【解决方案1】:

    不是打开和加载一个文件,而是遍历profile 目录中的所有文件名。加载每一个并将其存储在列表中以供以后使用。

    import glob
    import json    
    
    filenames_of_all_users = glob.glob("profile/*.json")
    users = []
    for filename in filenames_of_all_users:
        with open(filename) as file:
            users.append(json.load(file))
    
    users.sort(key=lambda user: user["xp"], reverse=True)
    
    output = ["'''"]
    for i, user in enumerate(users, 1):
        output.append(f"{i}. {user['name']}: {user['xp']} XP")
        if i == 20:
            break
    output.append("'''")
    result = "\n".join(output)
    print(result)
    

    我在这里进行了一些其他更改,这些更改对解决方案不是必不可少的,但更符合习惯和/或效率:

    • 使用enumerate而不是手动跟踪for循环中的索引
    • 使用join() 而不是用+= 连接字符串

    【讨论】:

      猜你喜欢
      • 2021-05-07
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 1970-01-01
      • 2016-05-11
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多