在列表中的元素中搜索子字符串,然后删除该元素 [英] Searching for substring in element in a list an deleting the element
本文介绍了在列表中的元素中搜索子字符串,然后删除该元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个列表,我正在尝试删除其中包含'pie'
的元素.这就是我所做的:
I have a list and I am trying to delete the elements that have 'pie'
in them. This is what I've done:
['applepie','orangepie', 'turkeycake']
for i in range(len(list)):
if "pie" in list[i]:
del list[i]
我一直使列表索引超出范围,但是当我将del
更改为print
语句时,它可以很好地打印出元素.
I keep getting list index out of range, but when I change the del
to a print
statement it prints out the elements fine.
推荐答案
与其从正在迭代的列表中删除项目,不如尝试使用Python不错的
Instead of removing an item from the list you're iterating over, try creating a new list with Python's nice list comprehension syntax:
foods = ['applepie','orangepie', 'turkeycake']
pieless_foods = [f for f in foods if 'pie' not in f]
这篇关于在列表中的元素中搜索子字符串,然后删除该元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文