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  
    版权声明:本文为博主原创文章,转载请附上博文链接!

  • 相关阅读:
    URAL——DFS找规律——Nudnik Photographer
    URAL1353——DP——Milliard Vasya's Function
    URAL1203——DPor贪心——Scientific Conference
    递推DP HDOJ 5389 Zero Escape
    区间DP UVA 1351 String Compression
    树形DP UVA 1292 Strategic game
    Manacher HDOJ 5371 Hotaru's problem
    同余模定理 HDOJ 5373 The shortest problem
    递推DP HDOJ 5375 Gray code
    最大子序列和 HDOJ 1003 Max Sum
  • 原文地址:https://www.cnblogs.com/fengff/p/10483596.html
Copyright © 2011-2022 走看看