在Python中,如何從對象數組中刪除對象?就像這樣:從python中的對象列表中刪除對象
x = object()
y = object()
array = [x,y]
# Remove x
我試過array.remove()
但它只是一個值,而不是數組中的特定位置的作品。我需要能夠通過解決其位置(remove array[0]
)
在Python中,如何從對象數組中刪除對象?就像這樣:從python中的對象列表中刪除對象
x = object()
y = object()
array = [x,y]
# Remove x
我試過array.remove()
但它只是一個值,而不是數組中的特定位置的作品。我需要能夠通過解決其位置(remove array[0]
)
del array[0]
其中0
是對象在list索引要刪除的對象(在Python沒有數組)
在蟒有沒有數組,列表被用來代替。有多種方法可以從列表中刪除對象:
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]
您應該更新第二個你的答案的一部分,並讓他使用.pop(0),因爲他特別詢問有關刪除位置。 – redreinard 2014-12-15 21:02:01
編輯redreinard,謝謝指出。 – 2014-12-16 22:23:47
,如果你想刪除最後一個只是做your_list.pop(-1)
如果你想刪除第一個your_list.pop(0)
或任何你想刪除的索引
如果你知道數組的位置,你可以將它傳遞給自己。如果您要移除多個項目,建議您按相反順序移除它們。
#Setup array
array = [55,126,555,2,36]
#Remove 55 which is in position 0
array.remove(array[0])
這不是一個數組。 – 2012-03-17 23:36:02
可能重複的[如何從Python中的列表中刪除元素?](http://stackoverflow.com/questions/2056341/how-to-delete-element-from-list-in-python) – Acorn 2012-03-17 23:38:07