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)
    
复制代码

 

 

 错误的根本原因:在删除列表前面的元素后,引起了列表后面元素向前挪动,元素的索引发生改变,此时再依据索引进行删除,发生错误

 

解决方案:

  1. delete all odd index items in one go using slice
    del lst[1::2]

     

     

  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]

      

  3. 倒序删除,后面的元素发生移动,但是已无影响
    复制代码
    b=list(range(10))
    for p in range(len(b)-1,-1,-2):
        b.pop(p)
    else:
        print(b)
    复制代码

      

  4. 构造新列表
    复制代码
    b=list(range(10))
    p=[]
    for v in range(len(b)):
        if v&1:
            pass
        else:
            p.append(b[v])
    else:
        print(p)
    复制代码

     

     

Dictionary:

  1. ebb = dict(zip('abcde', (11, 22, 11, 33, 22)))
    
    print(ebb)
    
    for key in list(ebb.keys()):  # 不能直接迭代ebb.keys()
        print(ebb.pop(key))

     

posted @   ascertain  阅读(287)  评论(0编辑  收藏  举报
编辑推荐:
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示