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))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律