2014-01-09 34 views
3

我的問題是我有一個列表 例如。一次刪除列表中的多個索引 - python

lst = [2, 5, 7, 12, 13] 


lst.pop(3) #12 
lst.pop(4) #13 

由於lst [3]已被移除lst [4]不再存在(超出範圍)。這給了我一個錯誤。現在我知道你會說改變你的代碼如下:...

lst.pop(4) #13 
lst.pop(3) #12 

...它生病修復錯誤,但我的問題是我實際的代碼是「啪」的隨機數,因此必須同時完成所有工作以避免錯誤。

有沒有在同一時間「啪」的任何方法...像類似這樣的東西:

lst.pop(3, 4) #12 and 13 at once 

感謝您的任何答案。

+0

不要使用'list'作爲變量名;你掩蓋了內置的類型。 –

+1

[如何同時從列表中刪除多個索引?](http:// stackoverflow。com/questions/11303225/how-to-remove-multiple-indexes-from-a-list-at-the-the-the-time) –

回答

11

您可以使用列表理解重建列表:

indices = {3, 4} 
newlist = [v for i, v in enumerate(oldlist) if i not in indices] 

我用了一套這裏的指數,作爲集合成員測試比列表更快。

請注意,刪除(最好使用del lst[index])部分重建列表;這樣在列表理解中使用一個循環可以更高效。

演示:

>>> oldlist = [2, 5, 7, 12, 13] 
>>> indices = {3, 4} 
>>> [v for i, v in enumerate(oldlist) if i not in indices] 
[2, 5, 7] 
+0

這與我上面的例子有什麼關係? –

+0

@ DennisCallanan:正如我發佈的那樣;我也給你一個快速演示會議。 –

+0

感謝一家工廠!只是好奇,如果我有一個程序每秒鐘循環多次運行它。這種方法會慢得多,只是從列表中「彈出」兩個數字? –

3

你可以用一個列表理解,這將創造一個新的列表中刪除:

>>> lst = [2, 5, 7, 12, 13] 
>>> [v for i, v in enumerate(lst) if i not in {4,3}] 
[2, 5, 7] 

你只需要這個新的列表再次分配給lst

0

你可以使用numpy索引來做到這一點。

0

如果你真的想就地刪除要做到這一點,答案顯然是給指數排序,刪除:

>>> lst = [2, 5, 7, 12, 13] 
>>> indices = {3, 4} 
>>> for index in sorted(indices, reverse=True): 
...  del lst[index] 
>>> print(lst) 
[2, 5, 7] 

但是,請注意,這是兩倍多的代碼的Martijn名單理解。如果你試圖用最優化的方式來做這件事情,(a)幾乎肯定是一種不成熟的優化,(b)它很可能是一種悲觀化。

如果你這樣做是因爲一些其他的代碼有lst的引用,你需要看到的變化,你仍然可以使用列表解析,用切片分配在一起:

>>> lst[:] = [v for i, v in enumerate(lst) if i not in indices] 

這裏,我們正在創建一個新列表,然後用該新列表替換表示lst的全部內容的子切片。

0
lst = [2, 5, 7, 12, 13] 

indexes = [3, 4] 
to_del = object() 

for index in indexes: 
    lst[index] = to_del 

for _ in indexes: 
    lst.remove(to_del) 

print(lst) 

[2, 5, 7] 
+2

如果你想要一個安全的哨兵,你總是可以使用'to_del = object()'。結果永遠不會與除自身以外的任何對象進行比較(或散列)。 – abarnert

+0

@abarnert謝謝+。 –

相關問題