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

Upv*_*ote 1 python loops

Object是一个解码的json对象,包含一个名为items的列表.

obj = json.loads(response.body_as_unicode())

for index, item in enumerate(obj['items']):
   if not item['name']:
       obj['items'].pop(index)
Run Code Online (Sandbox Code Playgroud)

我迭代这些项目,并希望在满足某个条件时删除项目.但是这没有按预期工作.经过一些研究后,我发现无法从列表中删除项目,同时在python中迭代此列表.但我无法将上述解决方案应用于我的问题.我尝试过一些不同的方法

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)
Run Code Online (Sandbox Code Playgroud)

但这会删除所有项目,而不仅仅是没有名称的项目.任何想法如何解决这个问题?

Mar*_*ers 6

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

相反,重建列表减去要删除的项目,并使用过滤器进行列表推导:

obj['items'] = [item for item in obj['items'] if item['name']]
Run Code Online (Sandbox Code Playgroud)

或者首先创建列表的副本以进行迭代,以便删除不会改变迭代:

for item in obj['items'][:]:  # [:] creates a copy
   if not item['name']:
       obj['items'].remove(item)
Run Code Online (Sandbox Code Playgroud)

您确实创建了一个副本,但是通过循环删除您要从中删除的列表来忽略该副本.


Mic*_*ort 5

使用while循环并根据需要更改迭代器:

obj = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

# remove all items that are smaller than 5
index = 0
# while index in range(len(obj)): improved according to comment
while index < len(obj):
    if obj[index] < 5:
        obj.pop(index)
        # do not increase the index here
    else:
        index = index + 1

print obj
Run Code Online (Sandbox Code Playgroud)

请注意,在for循环中不能更改迭代变量。它将始终设置为迭代范围内的下一个值。因此,问题不在于enumerate函数,而在于for循环。

将来请提供可验证的示例。在示例中使用 json 对象是不明智的,因为我们没有这个对象。