2012-03-29 105 views
1

我該如何去將數組項從數組中刪除,以保持增量列表中的數組索引?刪除數組項並更新數組索引

基本上我想這樣做:

修改下面陣列,使其結果在接下來的一個

#before 
arrayName[0] = "asdf random text" 
arrayName[1] = "more randomasdf" 
arrayName[2] = "this is the array item i am about to remove" 
arrayName[3] = "another asdfds" 
arrayName[4] = "and som easdf" 

#after 
arrayName[0] = "asdf random text" 
arrayName[1] = "more randomasdf" 
arrayName[2] = "another asdfds" 
arrayName[3] = "and som easdf" 

注意如何arrayName中的[2]從#before陣列中的#不見了在數組和索引已重新排序後,使#before數組中的arrayName [3]現在是arrayName [2]。

我想刪除數組項並重新排列數組索引。

我該如何有效地做到這一點?

+1

我猜「數組」你是指一個普通的Python列表,對吧? (Python中沒有內建的數組類型,但標準庫中有一個'array'模塊,有些人在Python的上下文中使用「array」來引用NumPy數組,而沒有明確地說明) – 2012-03-29 00:29:46

回答

5

如果 「數組」 你實際上意味着 「名單」,你可以簡單地使用del

del arrayName[2] 
+0

這是有效的。應該更有可能研究。謝謝。 – maxhud 2012-03-29 00:32:56

0

只使用德爾命令

del(arrayName[2]) 

Python會自動重新定購爲你

1
>>> a = ["asdf random text", "more randomasdf", "this is the array item i am about to remove", "another asdfds", "and som easdf",] 
>>> a 
['asdf random text', 'more randomasdf', 'this is the array item i am about to remove', 'another asdfds', 'and som easdf'] 
>>> a.pop(2) 
'this is the array item i am about to remove' 
>>> a 
['asdf random text', 'more randomasdf', 'another asdfds', 'and som easdf'] 
0

假設數組是一個python列表,你可以試試del arrayName[2]arrayName.pop(2)。每個刪除的複雜度是O(N),N是列表的長度。

如果arrayName的長度或要刪除的索引數很大,可以試試這個。

indexestodelete = set(2,.....) 
arrayName[:] = [arrayName[index] for index not in indexestodelete ]