在 Python 中,如何从对象列表中删除对象?像这样:
x = object()
y = object()
array = [x, y]
# Remove x
我试过 array.remove()
但它只适用于一个值,而不是数组中的特定位置。我需要能够通过寻址对象的位置来删除对象(remove array[0]
)。
最佳答案
有多种方法可以从列表中删除对象:
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
在您的情况下,使用的适当方法是 pop
,因为它需要删除索引:
x = object()
y = object()
array = [x, y]
array.pop(0)
# Using the del statement
del array[0]
关于python - 从python中的对象列表中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9754729/