2012-03-29 110 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 ]