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

2024-05-16 13:01:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

我总是使list index超出范围,但是当我将del更改为print语句时,它会很好地打印出元素。在


Tags: in元素列表forindexlenifrange
3条回答

不要从正在迭代的列表中删除项,请尝试使用Python的nice list comprehension syntax创建一个新列表:

foods = ['applepie','orangepie', 'turkeycake']
pieless_foods =  [f for f in foods if 'pie' not in f]

在迭代期间删除元素,会更改大小,从而导致索引错误。在

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

L = [e for e in L if "pie" not in e]

比如:

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

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

相关问题 更多 >