json 尝试从最高值到最低值对排行榜命令进行排序

sgtfey8w  于 2022-11-19  发布在  其他
关注(0)|答案(1)|浏览(150)

我有一个排行榜,我试图从最高计数的成员到最低计数的成员排序,但我似乎无法做到这一点。排行榜代码:

@bot.command()
@commands.cooldown(1, 20, commands.BucketType.user) 
async def leaderboard(ctx):
    embed = discord.Embed(
         title="Leadboard",
         description="Your Servers Count",
         color=0xFF000
        )
    with open('messages.json') as file:
         data = json.load(file)
    for key, value in data[f"{ctx.guild.name}"].items():
        try:
            embed.add_field(name = key, value = value)
            embed.set_footer(text="If you feel your message's are not being counted, please get the server owner to send me a dm!")
        except: return
    await ctx.respond(embed=embed)

输出:Gyazo.com
这是一个我想要实现的例子Gyazo.com

xv8emn3q

xv8emn3q1#

最终答案:

#your imports [...]

from discord.utils import get
from operator import itemgetter
from tabulate import tabulate

#your declarations [...]

@bot.command()
@commands.cooldown(1, 20, commands.BucketType.user) 
    listValues = []
    sortedList = []

    embed = discord.Embed(
             title="Leadboard",
             description="Your Servers Count",
             color=0xFF000
            )
    
    with open('dat.json') as file:
        data = json.load(file)
        listValues = new_list = list(map(list, data[f"{ctx.guild.name}"].items()))
        
    sortedList = sorted(listValues, key=itemgetter(1), reverse=True)
    strToPrint = ""
    for item in sortedList : 
        strToPrint = strToPrint +"\n"+ item[0] +" : "+str(item[1])  
    embed.add_field(name="Scores", value=strToPrint )
    embed.set_footer(text="If you feel your message's are not being counted, please get the server owner to send me a dm!")
    await ctx.send(embed=embed)

在我这边尝试了几次之后,最简单的方法是创建一个json字典列表,Map该列表以获取键和值,并将其转换为一个新的列表。然后我将该列表转换为一个字符串,添加“\n”作为分隔符,并在排序后将得分转换为字符串。最后,我将结果字符串作为值传递给您的嵌入,然后..瞧:)

相关问题