我试图用 JSON 在 discord.py 上为我的关卡系统创建排行榜命令,但由于某种奇怪的原因,它不起作用。只显示前 3 名最高级别的球员,而不是前 5 名,当我尝试给另一个球员大量经验以改变第一名时,最后一名第一名的球员不会去第二名,但无处可寻.
这是输出图片,上面是我没有改变Void的exp时的输出,下面是我改变Void的exp时的输出。
# leaderboard command
@commands.command(name='leaderboard', aliases=['lb', 'top', 'levels'])
async def leaderboard(self, ctx, arg:str=None):
try:
with open(levelsJSON, 'r') as levels_file:
levels = json.load(levels_file)
## Top 5 places VARIABLES
first_name = 'N/A'
first_level = 0
first_exp = 0
second_name = 'N/A'
second_level = 0
second_exp = 0
third_name = 'N/A'
third_level = 0
third_exp = 0
fourth_name = 'N/A'
fourth_level = 0
fourth_exp = 0
fifth_name = 'N/A'
fifth_level = 0
fifth_exp = 0
## Variables END
# loops through the file
for user in levels:
exp = float(levels[user]['exp'])
level = float(levels[user]['level'])
name = levels[user]['name']
if exp > first_exp:
first_name = name
first_level = level
first_exp = exp
elif exp > second_exp:
second_name = name
second_level = level
second_exp = exp
elif exp > third_exp:
third_name = name
third_level = level
third_exp = exp
elif exp > fourth_exp:
fourth_name = name
fourth_level = level
fourth_exp = exp
elif exp > fifth_exp:
fifth_name = name
fifth_level = level
fifth_exp = exp
else:
pass
await ctx.send(f"1. {first_name}\n2. {second_name}\n3. {third_name}\n4. {fourth_name}\n5. {fifth_name}")
except Exception as error:
await ctx.send(f'```{error}```')
这是存储数据的 JSON 文件。
{
"586579525849186315": {
"name": "MythCraftMC#0963",
"level": 8,
"exp": 2174.21875,
"max_exp": 2562.890625
},
"658633474995126282": {
"name": "Regney#2226",
"level": 3,
"exp": 100.0,
"max_exp": 337.5
},
"586579523549196315": {
"name": "Void#0363",
"level": 0,
"exp": 32345,
"max_exp": 100
},
"586579522449186315": {
"name": "Universal_Kid#0963",
"level": 4,
"exp": 350,
"max_exp": 500
},
"586572525844186315": {
"name": "ThatOneGuy#0453",
"level": 3,
"exp": 300,
"max_exp": 400
}
}
[没有错误]
答案 0 :(得分:2)
尝试采用不同的实现方式。首先,我们可以制作一个列表来跟踪用户。
userList = []
for user in levels
exp = float(levels[user]['exp'])
level = float(levels[user]['level'])
name = levels[user]['name']
userList.append([exp, level, name])
userList = sorted(userList, key=lambda x:x[1], reverse=True)
这将用所有用户填充 userList,并根据级别对它们进行排序。然后,我们可以打印该列表中的前 x 项。
await ctx.send(f"1. {userList[0][2]}\n2. {userList[1][2]}\n3. {userList[2][2]}\n4. {userList[3][2]}\n5. {userList[4][2]}")
有了这个,你可以去掉代码中的所有变量名和所有 if 语句,让它像你想要的那样动态。