for in 语句只打印最后的结果

所以我正在使用可以查看机器人的命令进行测试。它将检测 arg 并查找 arg 是否在事物中,如果在事物中它将打印以下信息。但是,它仅适用于最后的信息。我该如何修复它?


命令代码:


@client.command(pass_context=True)

async def viewbot(ctx, arg):

            for bot in data['bots']:

                name = bot["name"]

                #createdby = bot["createdby"]

                briefdesc = bot["briefdesc"]

                desc = bot["description"]

                slug = bot["slug"]

            if arg == f'{slug}':

                embed = discord.Embed(title=name,description=briefdesc,timestamp=ctx.message.created_at,colour=discord.Color.dark_green())

                await ctx.send(embed = embed)

            else:

                print("no")

JSON 代码:


{

    "bots": [

        {

            "name": "Bot1",

            "createdby": "Bit#0258",

            "briefdesc": "Texts.",

            "description": "Test",

            "library": "discord.py",

            "slug": "bot1"

        },

        {

            "name": "Bot2",

            "createdby": "BotTest#0001",

            "briefdesc": "Text",

            "description": "Rext",

            "library": "discord.js",

            "slug": "bot2"

        }

    ]

}

如果您知道如何修复它,请回复此问题。谢谢。


千巷猫影
浏览 95回答 1
1回答

慕运维8079593

看看你的逻辑:        for bot in data['bots']:            name = bot["name"]            #createdby = bot["createdby"]            briefdesc = bot["briefdesc"]            desc = bot["description"]            slug = bot["slug"]        if arg == f'{slug}':            ...您特别告诉它遍历所有可用的机器人,提取它们的字段,并将每个字段写入前一组数据的顶部。当您离开循环时,每个变量中只有最新值。这就是变量的工作原理。要获取所有值,请将处理(if)移至循环内,或将数据收集在列表中而不是标量变量中。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python