在python中使用enumerate()时从列表中删除元素 [英] Remove element from list when using enumerate() in python
问题描述
Object是一个解码的json对象,其中包含一个称为items的列表.
Object is a decoded json object that contains a list called items.
obj = json.loads(response.body_as_unicode())
for index, item in enumerate(obj['items']):
if not item['name']:
obj['items'].pop(index)
我遍历这些项目,并希望在满足特定条件时删除该项目.但是,这没有按预期方式工作.经过一番研究,我发现无法同时从python中删除此列表中的项目.但是我不能将提到的解决方案应用于我的问题.我尝试了一些其他方法,例如
I iterate over those items and want to remove an item when a certain condition is met. However this is not working as expected. After some research I found out that one cannot remove items from a list while at the same time iterating of this list in python. But I cannot apply the mentioned solutions to my problem. I tried some different approaches like
obj = json.loads(response.body_as_unicode())
items = obj['items'][:]
for index, item in enumerate(obj['items']):
if not item['name']:
obj['items'].remove(item)
但是,这将删除所有项,而不仅仅是没有名称的项.有什么想法可以解决这个问题吗?
But this removes all items instead of just the one not having a name. Any ideas how to solve this?
推荐答案
在迭代列表时不要从列表中删除项目;迭代将跳过项目,因为迭代索引未更新以说明已删除元素
Don't remove items from a list while iterating over it; iteration will skip items as the iteration index is not updated to account for elements removed.
Instead, rebuild the list minus the items you want removed, with a list comprehension with a filter:
obj['items'] = [item for item in obj['items'] if item['name']]
或首先创建列表的副本进行迭代,以使删除不会更改迭代:
or create a copy of the list first to iterate over, so that removing won't alter iteration:
for item in obj['items'][:]: # [:] creates a copy
if not item['name']:
obj['items'].remove(item)
您确实创建了一个副本,但是然后通过循环从静止状态删除的列表来忽略该副本.
You did create a copy, but then ignored that copy by looping over the list that you are deleting from still.
这篇关于在python中使用enumerate()时从列表中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!