zoukankan      html  css  js  c++  java
  • python 遍历list并删除部分元素

    python 遍历list并删除部分元素
    https://blog.csdn.net/afgasdg/article/details/82844403
    有两个list,list_1 为0-9,list_2 为0-4,需要删除list_1中包含在list_2中的元素

    list_1 =[]
    for i in range(10):
        list_1.append(str(i))

    list_1

    ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

    list_2 =[]
    for i in range(5):
        list_2.append(str(i))
    list_2
    ['0', '1', '2', '3', '4']


    为了提高执行效率,可以将大的list转成set

    set_2 = set(list_2)

    set_2


    {'0', '1', '2', '3', '4'}

    错误删除方式1

    直接遍历list并删除元素,这种方式会导致删除之后的元素前移,后漏掉一部分元素

    temp = list_1[:]
    for item in temp:
        if item in set_2:
            temp.remove(item)


    "列表长度:%d, 列表:%s" % (len(temp), temp)

    "列表长度:7, 列表:['1', '3', '5', '6', '7', '8', '9']"

    错误删除方式2

    使用下标遍历输出,删除元素,同样也会出现删除只有的元素前移导致漏掉部分元素

    temp = list_1[:]
    for i in range(len(temp)):
        try:
            if temp[i] in set_2:
                temp.pop(i)
        except:# 这里下标会越界,为了结果好看,不做处理
            pass


    "列表长度:%d, 列表:%s" % (len(temp), temp)

    "列表长度:7, 列表:['1', '3', '5', '6', '7', '8', '9']"

    正确方式1;倒序

    倒序(保证 next 指向为未遍历过得)列表长度减少,但是next指向一直是为未遍历过的元素,并不会漏掉

    temp = list_1[:]
    for i in range(len(temp)-1, -1, -1):
        if temp[i] in set_2:
            temp.pop(i)


    "列表长度:%d, 列表:%s" % (len(temp), temp)

    "列表长度:5, 列表:['5', '6', '7', '8', '9']"

    正确方式2;遍历复制数组,修改原数组

    这种方式能保证遍历到所有元素

    temp = list_1[:]
    for item in temp[:]:
        if item in set_2:
            temp.remove(item)


    "列表长度:%d, 列表:%s" % (len(temp), temp)

    "列表长度:5, 列表:['5', '6', '7', '8', '9']"

    正确方式3;遍历需要删除的数组

    temp = list_1[:]
    for item in set_2:
        try:
            temp.remove(item)
        except: # 这里元素不存在会抛异常
            pass


    "列表长度:%d, 列表:%s" % (len(temp), temp)

    "列表长度:5, 列表:['5', '6', '7', '8', '9']"

    正确方式4;利用集合差集,不能保证顺序

    temp = list_1[:]
    temp = list(set(temp).difference(set_2))


    "列表长度:%d, 列表:%s" % (len(temp), temp)


    "列表长度:5, 列表:['8', '9', '5', '7', '6']"
    ---------------------  
    作者:java爱好者  
    来源:CSDN  
    原文:https://blog.csdn.net/afgasdg/article/details/82844403  
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    教你如何用Meterpreter渗透Win系统
    Maven 自动打包上传到私服 Nexus
    从同事的一个提问想到的学习途径
    SAS学习笔记之《SAS编程与数据挖掘商业案例》(1)系统简介和编程基础
    StackOverflowError&OutOfMemoryError区别
    优先使用TimeUnit类中的sleep()
    Java 开源博客 Solo 1.3.0 发布
    Java 开源博客 Solo 1.3.0 发布
    Cleanup failed to process the following paths错误的解决
    Java&Xml教程(六)使用JDOM解析XML文件
  • 原文地址:https://www.cnblogs.com/fengff/p/10483596.html
Copyright © 2011-2022 走看看