且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从python中的对象列表中删除对象

更新时间:2023-12-04 20:31:34

在 python 中没有数组,而是使用列表.有多种方法可以从列表中删除对象:

In python there are no arrays, lists are used instead. There are various ways to delete an object from a list:

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,因为它需要删除索引:

In your case the appropriate method to use is pop, because it takes the index to be removed:

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