2012-03-17 108 views
26

在Python中,如何从对象数组中删除对象?就像这样:从python中的对象列表中删除对象

x = object() 
y = object() 
array = [x,y] 
# Remove x 

我试过array.remove()但它只是一个值,而不是数组中的特定位置的作品。我需要能够通过解决其位置(remove array[0]

+5

这不是一个数组。 – 2012-03-17 23:36:02

+2

可能重复的[如何从Python中的列表中删除元素?](http://stackoverflow.com/questions/2056341/how-to-delete-element-from-list-in-python) – Acorn 2012-03-17 23:38:07

回答

4
del array[0] 

其中0是对象在list索引要删除的对象(在Python没有数组)

57

在蟒有没有数组,列表被用来代替。有多种方法可以从列表中删除对象:

my_list = [1,2,4,6,7] 

del my_list[1] # Removes index 1 from the list 
print my_list # [1,4,6,7] 
my_list.remove(4) # Removes the integer 4 from the list, not the index 4 
print my_list # [1,6,7] 
my_list.pop(2) # Removes index 2 from the list 

在你的情况适当的方法来使用的流行,因为它需要的索引中删除:

x = object() 
y = object() 
array = [x, y] 
array.pop(0) 
# Using the del statement 
del array[0] 
+1

您应该更新第二个你的答案的一部分,并让他使用.pop(0),因为他特别询问有关删除位置。 – redreinard 2014-12-15 21:02:01

+1

编辑redreinard,谢谢指出。 – 2014-12-16 22:23:47

-1

,如果你想删除最后一个只是做your_list.pop(-1) 如果你想删除第一个your_list.pop(0)或任何你想删除的索引

1

如果你知道数组的位置,你可以将它传递给自己。如果您要移除多个项目,建议您按相反顺序移除它们。

#Setup array 
array = [55,126,555,2,36] 
#Remove 55 which is in position 0 
array.remove(array[0])