Python: remove item during iteration
错误示例:
lst=list(range(10))
def remove_odd_index_elements(lst):
b=0
for item in lst:
if b&1:
lst.remove(item)
else:
pass
b+=1
remove_odd_index_elements(lst)
print(lst)
错误的根本原因:在删除列表前面的元素后,引起了列表后面元素向前挪动,元素的索引发生改变,此时再依据索引进行删除,发生错误
解决方案:
- delete all odd index items in one go using slice
del lst[1::2]
-
You cannot delete elements from a list while you iterate over it, because the list iterator doesn't adjust as you delete items. See Loop "Forgets" to Remove Some Items what happens when you try.
An alternative would be to build a new list object to replace the old, using a list comprehension with enumerate() providing the indices:
利用列表解析式重新构造新列表,避免了删除操作[c for p,c in enumerate(b) if not p%2]
- 倒序删除,后面的元素发生移动,但是已无影响
b=list(range(10)) for p in range(len(b)-1,-1,-2): b.pop(p) else: print(b)
- 构造新列表
b=list(range(10)) p=[] for v in range(len(b)): if v&1: pass else: p.append(b[v]) else: print(p)
Dictionary:
-
ebb = dict(zip('abcde', (11, 22, 11, 33, 22))) print(ebb) for key in list(ebb.keys()): # 不能直接迭代ebb.keys() print(ebb.pop(key))