discord.ext.commands.errors.CommandInvokeError:命令引发异常:IndexError:列表索引超出范围

时间:2021-06-17 17:00:28

标签: python discord discord.py

当我遍历我的 json 文件时,它没有显示最后一个

for i in range(len(data)):
    print(i)
    if data[i]["id"] == user.id and data[i]["infractionType"] == "Warning":
        print("removed")
        data.remove(data[i])

这是打印出来的

ready
0
removed
1
removed
2

2 个答案:

答案 0 :(得分:0)

根据评论中的建议,在遍历列表时删除元素并不是一个好主意。最简单的解决方法是在循环后移除元素。

toRemove = []
for i in range(len(data)):
print(i)
if data[i]["id"] == user.id and data[i]["infractionType"] == "Warning":
    print("removed")
    toRemove.append(i)
for i in toRemove:
    data.remove(data[i])

答案 1 :(得分:0)

试试看:

index = 0
for i in range(len(data)):
    print(i)
    if data[index]["id"] == user.id and data[index]["infractionType"] == "Warning":
        print("removed")
        data.pop(0)
    else:
        index += 1

并检查它:

>>> a = [1, 2, 1, 3, 4, 5]
>>> len(a)
6
>>> a.remove(1)
>>> a
[2, 3, 4, 5]
>>> len(a)
4
# -------------------------------
>>> a = [1, 2, 1, 3, 4, 5]
>>> len(a)
6
>>> a.pop(0)
>>> a
[2, 1, 3, 4, 5]
>>> len(a)
5