Python 为什么在下面的代码中出现索引器错误:列表索引超出范围错误?

Python 为什么在下面的代码中出现索引器错误:列表索引超出范围错误?,python,function,debugging,Python,Function,Debugging,我只是想删除传递的单词的副本,但它不起作用 wordlist = ["a", "a", 'b', "b", "b", "c", "d", "e"] new_list = wordlist word = "a" for i in range(len(wordlist)): if wordlist[i] == word:

我只是想删除传递的单词的副本,但它不起作用

wordlist = ["a", "a", 'b', "b", "b", "c", "d", "e"]
new_list = wordlist
word = "a"

for i in range(len(wordlist)):
    if wordlist[i] == word:
        new_list.remove(word)

print(new_list)

新列表
制作为真正的浅层副本:

new_list = wordlist[:]
否则,
new\u list
只不过是对同一列表对象的另一个引用,您最初创建的范围达到了在两次删除后不再存在的索引

或者(更好)从头开始构建:

new_list = [w for w in word_list if w != word]

新列表
制作为真正的浅层副本:

new_list = wordlist[:]
否则,
new\u list
只不过是对同一列表对象的另一个引用,您最初创建的范围达到了在两次删除后不再存在的索引

或者(更好)从头开始构建:

new_list = [w for w in word_list if w != word]

因为
new\u list
wordlist
指向同一个对象。您应该使用
new\u list=wordlist.copy()
创建列表的副本

wordlist = ["a", "a", 'b', "b", "b", "c", "d", "e"]
new_list = wordlist.copy()
word = "a"

for i in range(len(wordlist)):
    if wordlist[i] == word:
        new_list.remove(word)

print(new_list)

注意:不建议在对容器进行迭代时修改容器。

因为
new\u list
wordlist
指向同一对象。您应该使用
new\u list=wordlist.copy()
创建列表的副本

wordlist = ["a", "a", 'b', "b", "b", "c", "d", "e"]
new_list = wordlist.copy()
word = "a"

for i in range(len(wordlist)):
    if wordlist[i] == word:
        new_list.remove(word)

print(new_list)
注意:不建议在对容器进行迭代时修改容器。

这一点解释得很好

为了让它工作,你必须明确要求一份副本

wordlist = ["a", "a", 'b', "b", "b", "c", "d", "e"]
new_list = list(wordlist)

word = "a"

for i in range(len(wordlist)):
    if wordlist[i] == word:
        new_list.remove(word)

print(new_list)
这解释得很好

为了让它工作,你必须明确要求一份副本

wordlist = ["a", "a", 'b', "b", "b", "c", "d", "e"]
new_list = list(wordlist)

word = "a"

for i in range(len(wordlist)):
    if wordlist[i] == word:
        new_list.remove(word)

print(new_list)

new_list和wordlist在您的案例中是同一个对象。id(new_list)等于id(wordlist)。注意python中的易变性。如果顺序无关紧要,最简单的方法是
new\u list=list(set(wordlist))
new\u list和wordlist在您的例子中是同一个对象。id(new_list)等于id(wordlist)。注意python中的易变性。如果顺序无关紧要,最简单的方法是
new\u list=list(set(wordlist))