python 遍歷list並刪除部分元素

python 遍歷list並刪除部分元素

有兩個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']"
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章