Python 在列表中的元素中搜索子字符串并删除该元素

Python 在列表中的元素中搜索子字符串并删除该元素,python,list,search,element,substring,Python,List,Search,Element,Substring,我有一个列表,我正在尝试删除其中包含'pie'的元素。这就是我所做的: ['applepie','orangepie', 'turkeycake'] for i in range(len(list)): if "pie" in list[i]: del list[i] 我一直将列表索引超出范围,但当我将del更改为print语句时,它会很好地打印出元素 出现错误的原因是删除某些内容时更改了列表的长度 例如: first loop: i = 0, length of l

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

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

我一直将列表索引超出范围,但当我将
del
更改为
print
语句时,它会很好地打印出元素

出现错误的原因是删除某些内容时更改了列表的长度

例如:

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)
stuff = ['applepie','orangepie', 'turkeycake']
stuff = [item for item in stuff if not item.endswith('pie')]

在迭代过程中删除元素会更改大小,从而导致索引错误

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


另一个较长的方法是记下遇到饼图的索引,并在第一个for循环之后删除这些元素,而不是从正在迭代的列表中删除一个项目,尝试使用Python的nice创建一个新列表:

比如:

for item in in list:
    if "pie" not in item:
        new list.append(item)
stuff = ['applepie','orangepie', 'turkeycake']
stuff = [item for item in stuff if not item.endswith('pie')]

修改你正在迭代的对象应该被认为是不可行的。

foods=['applepie'、'orangepie'、'turkeycake']pie_foods=[f代表食物中的f,如果“pie”不在f中]
(不确定“not in”是否是正确的语法。@AJ.谢谢,我的意思是错误的-我已经纠正了这个非常简短的答案。这将是最简单的解决方案如果
'pie'
总是在末尾,你可以使用
endswith
字符串方法。这样会更有效(对于长字符串,对于短字符串,这几乎是一样的)如果这是您想要做的,则更清晰。(另请注意:还有
startswith
exist)。您仍然存在相同的问题-除非按相反的顺序删除元素。但这仍然不高效,因为删除一个元素意味着每次都必须对后面的所有元素进行洗牌。创建一个新列表非常高效,您不是在复制元素,而是在创建对它们的额外引用。