2016-07-23 173 views
1

Object是一个解码的json对象,它包含一个名为items的列表。在python中使用枚举()时从列表中删除元素

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

for index, item in enumerate(obj['items']): 
    if not item['name']: 
     obj['items'].pop(index) 

我遍历这些项目,并希望在满足某些条件时删除项目。然而,这并不像预期的那样工作。经过一番研究之后,我发现无法从列表中删除项目,同时在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) 

但是,这将删除所有项目,而不是只有一个没有名称。任何想法如何解决这个问题?

+1

我认为你在第二种情况下有一个拼写错误:'对于索引,列举项目(项目)' –

回答

5

不要在迭代列表时从列表中删除项目;迭代将skip items作为迭代索引不会更新以说明删除的元素。

相反,重建列表中减去你想删除的项目,用带有过滤器的list comprehension

obj['items'] = [item for item in obj['items'] if item['name']] 

或创建列表的副本第一个迭代,以实现删除韩元“T改变迭代:

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

你没有创建一个副本,但随后忽略通过循环复制OVE r你从静止删除的列表。

2

使用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 

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

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

+0

为什么非常详细和(特别是对于Python 2,非常昂贵)'范围内的索引(len(obj) )'?为什么不只是'index

+0

我会说这是问题中的一个细节。基本部分是while和for循环之间的区别,以及当列表项被弹出时处理while循环的迭代器。然而你是对的:你的建议改善了这个细节。 –