且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在python中使用enumerate()时从列表中删除元素

更新时间:2023-11-05 21:20:34

在迭代列表时不要从列表中删除项目;迭代将跳过项目,因为迭代索引未更新以说明已删除元素

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.