Python語法糖——遍歷列表時刪除元素

Python的for能夠遍歷一個List,可是在遍歷的過程當中刪除元素經常會獲得意想不到的結果甚至程序出現異常,例如:數組

lst = [1, 1, 0, 2, 0, 0, 8, 3, 0, 2, 5, 0, 2, 6]

for item in lst:
    if item == 0:
        lst.remove(item)
print lst

輸出: [1, 1, 2, 8, 3, 2, 5, 0, 2, 6]安全

這段代碼的本意是想刪除列表中元素爲 0 的項,但實際跑起來並非那個結果。函數

再看下面這個例子,利用索引來遍歷刪除列表中的元素:code

for item in range(len(lst)):
    if lst[item] == 0:
        del lst[item]
print lst

輸出: IndexError: list index out of range索引

這時候就報錯了,拋出了數組下標越界的異常。緣由是用for發起任何形式的遍歷時,它的遍歷順序都是從最初就肯定的,而在遍歷中刪除了元素會致使當前索引的變化,這樣一是會致使漏刪元素,二是會致使遍歷超過鏈表的長度。rem

因此遍歷一個List時要刪除其中的部分元素就須要其餘的解決方案。it

方法一:能夠使用filter過濾返回新的Listio

lst = [1, 1, 0, 2, 0, 0, 8, 3, 0, 2, 5, 0, 2, 6]

lst = filter(lambda x: x != 0, lst)
print lst

這樣能夠安全刪除列表中值爲 0 的元素了,filter包括兩個參數,分別是functionlistfilter把傳入的函數依次做用於每一個元素,而後根據返回值是True仍是False來決定是保留仍是丟棄該元素。function

方法二:列表解析lambda

lst = [x for x in lst if x != 0]
print lst

方法三:或者遍歷拷貝的List,操做原始的List

for item in lst[:]:
    if item == 0:
        lst.remove(item)
print lst

方法四:while循環來搞定,每次循環都先會判斷 0 是否在列表中

while 0 in lst:
    lst.remove(0)
print lst

方法五:倒序循環遍歷

for item in range(len(lst) - 1, -1, -1):
    if lst[item] == 0:
        del lst[item]
print lst

倒序是最geek的解決辦法,可是倒序的代碼可讀性差,推薦用filter,這樣寫出來的代碼更Pythonic。

相關文章
相關標籤/搜索