4

我有一个列表,我正在尝试删除其中的元素'pie'。这就是我所做的:

['applepie','orangepie', 'turkeycake']
for i in range(len(list)):
    if "pie" in list[i]:
         del list[i]

我不断使列表索引超出范围,但是当我将其更改delprint语句时,它会很好地打印出元素。

4

5 回答 5

6

不要从您正在迭代的列表中删除一个项目,而是尝试使用 Python 的漂亮列表理解语法创建一个新列表:

foods = ['applepie','orangepie', 'turkeycake']
pieless_foods =  [f for f in foods if 'pie' not in f]
于 2012-10-18T11:16:18.443 回答
2

在迭代过程中删除元素,会改变大小,导致 IndexError。

您可以将代码重写为(使用列表理解)

L = [e for e in L if "pie" not in e]
于 2012-10-18T11:15:23.343 回答
2

就像是:

stuff = ['applepie','orangepie', 'turkeycake']
stuff = [item for item in stuff if not item.endswith('pie')]

修改您正在迭代的对象应该被视为不可行。

于 2012-10-18T11:21:51.560 回答
1

您收到错误的原因是因为您在删除某些内容时更改了列表的长度!

例子:

first loop: i = 0, length of list will become 1 less because you delete "applepie" (length is now 2)
second loop: i = 1, length of list will now become just 1 because we delete "orangepie"
last/third loop: i = 2, Now you should see the problem, since i = 2 and the length of the list is only 1 (to clarify only list[0] have something in it!).

所以宁愿使用类似的东西:

for item in in list:
    if "pie" not in item:
        new list.append(item)
于 2012-10-18T11:14:24.353 回答
0

另一种但更长的方法是记下遇到 pie 的索引并在第一个 for 循环后删除这些元素

于 2012-10-18T11:16:02.013 回答