Skip to main content
 首页 » 编程设计

python之删除数组项并更新数组索引

2025年05月04日18shihaiming

我将如何以将数组索引保留在增量列表中的方式从数组中删除数组项?

基本上我想这样做:

修改下面的数组,使其结果为下一个

#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" 

请注意#before 数组中的 arrayName[2] 如何消失在#after 数组中,并且索引已重新排序,因此#before 数组中的 arrayName[3] 现在是 arrayName[2]。

我想删除数组项并重新排序数组索引。

我怎样才能有效地做到这一点?

请您参考如下方法:

如果您所说的“数组”实际上是指“列表”,您可以简单地使用 del:

del arrayName[2]