zoukankan      html  css  js  c++  java
  • python循环删除列表元素常见错误与正确方法

    python循环删除列表元素

    觉得有用的话,欢迎一起讨论相互学习~

    我的微博我的github我的B站

    常见错误

    常见错误一:使用固定长度循环删除列表元素

    # 使用固定长度循环pop方法删除列表元素
    num_list_1 = [1, 2, 2, 2, 3]
    
    for i in range(len(num_list_1)):
        if num_list_1[i] == 2:
            num_list_1.pop(i)
        else:
            print(num_list_1[i])
    
    print("num_list_1:", num_list_1)
    # IndexError: list index out of range
    
    • 原因是在删除list中的元素后,list的实际长度变小了,但是循环次数没有减少,依然按照原来list的长度进行遍历,所以会造成索引溢出

    常见错误二:正序循环遍历删除列表元素

    • 不能删除连续的情况
    # 正序循环遍历删除列表元素
    num_list_2 = [1, 2, 2, 2, 3]
    
    for item in num_list_2:
        if item == 2:
            num_list_2.remove(item)
        else:
            print("item", item)
        print("num_list_2", num_list_2)
    
    print("after remove op", num_list_2)
    
    # item 1
    # num_list [1, 2, 2, 2, 3]
    # num_list [1, 2, 2, 3]
    # num_list [1, 2, 3]
    # after remove op [1, 2, 3]
    

    • 思考了下,知道了原因,当符合条件,删除元素[2]之后,后面的元素全部往前移,但是索引并不会随着值向前移动而变化,而是接着上一个位置向后移动。这样就会漏掉解

    正确的方法

    正确的方法一:倒序循环遍历

    # 倒序循环遍历删除列表元素
    num_list_3 = [1, 2, 2, 2, 3]
    
    for item in num_list_3[::-1]:
        if item == 2:
            num_list_3.remove(item)
        else:
            print("item", item)
        print("num_list_3", num_list_3)
    
    print("after remove op", num_list_3)
    
    # item 3
    # num_list_3 [1, 2, 2, 2, 3]
    # num_list_3 [1, 2, 2, 3]
    # num_list_3 [1, 2, 3]
    # num_list_3 [1, 3]
    # item 1
    # num_list_3 [1, 3]
    # after remove op [1, 3]
    

    正确的方法二:遍历拷贝的list,操作原始的list

    • 原始的list是num_list,那么其实,num_list[:]是对原始的num_list的一个拷贝,是一个新的list,所以,我们遍历新的list,而删除原始的list中的元素,则既不会引起索引溢出,最后又能够得到想要的最终结果。此方法的缺点可能是,对于过大的list,拷贝后可能很占内存。那么对于这种情况,可以用倒序遍历的方法来实现。
    # 遍历拷贝的list,操作原始的list
    num_list_4 = [1, 2, 2, 2, 3]
    
    for item in num_list_4[:]:
        if item == 2:
            num_list_4.remove(item)
        else:
            print("item", item)
    
        print("num_list_4", num_list_4)
    
    print("after remove op", num_list_4)
    
    # item 1
    # num_list_4 [1, 2, 2, 2, 3]
    # num_list_4 [1, 2, 2, 3]
    # num_list_4 [1, 2, 3]
    # num_list_4 [1, 3]
    # item 3
    # num_list_4 [1, 3]
    # after remove op [1, 3]
    
  • 相关阅读:
    js下拉框二级关联菜单效果代码具体实现
    js实现拉伸拖动iframe的具体代码
    mysql--Ubuntu下设置MySQL字符集为utf8
    python--使用MySQL数据库
    python--笨方法学python 习题52
    python--web.py使用
    python--flask使用
    python--类方法、对象方法、静态方法
    Python--类定义
    堆 在游戏中的运用
  • 原文地址:https://www.cnblogs.com/cloud-ken/p/10021266.html
Copyright © 2011-2022 走看看