繁体   English   中英

Python Indexerror:使用 index() 时列表索引超出范围

[英]Python Indexerror: list index out of range while using index()

@bot.command()
async def start(ctx):
    edit = []
    with open("wallet.json", "w") as file:
        for obj in file:
            dict = json.load(obj)
            edit.append(dict)

    userid = []
    for player in edit:
        userid.append(str(player["id"]))

    user = str(ctx.author.id)
    if userid.count(user) > 0:
        await ctx.reply("You already have an account")
    else:
        embed = nextcord.Embed(title = "Welcome to the Kingdoms of Sulphae!", description = "Sulphae is a place where people can grind for resources, conquer other factions, and become the greatest king to ever exist! Enjoy your stay!")
        embed.set_footer(text = "Made by Energia360, a really pog dude who decided to dedicate his summer break to making a Discord bot")
        await ctx.send(embed = embed)
        userid.append(user)

        edit[userid.index(user)]["id"] = user
        edit[userid.index(user)]["gold"] = 0
        edit[userid.index(user)]["fyre"] = 0
        edit[userid.index(user)]["faction"] = None

    json.dump(edit, file)

我在 Python 中有一段用于 Discord 机器人的代码(我确信这对于这个特定问题并不重要)。 json 文件 wallet.json 为空。 这段代码给了我一个 Indexerror

edit[userid.index(user)]["id"] = user

我的这部分代码。

    edit[userid.index(user)]["id"] = user
IndexError: list index out of range

这是我收到的错误消息。

我不确定 index() 函数如何提供超出范围的错误。 解决方案赞赏。

更新:在添加一个简单的 print() 来查看userid.index(user)是什么之后,我发现它是 0。这没有触发任何错误,所以在 json 括号中使用一些东西可能是问题所在。

更新 2:将userid.index(user)移出括号并创建一个变量来存储它,但没有用。 也许实际上是触发错误的“id”。

来自userid的所有用户最初都来自edit 如果用户不在userid中,它肯定不在edit中。

当您在userid找不到用户时,将其 id 附加到userid中,但不进行edit userid将比edit长。 不仅如此,由于您将用户附加到userid ,它将位于列表的末尾,一个保证在edit中不存在的索引。 这就是您收到IndexError的原因。

一种解决方案是构建整个用户对象并将其附加到edit 您的代码有点不清楚,可以通过其他方式进行改进,但这将是使其不中断的第一步。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM