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

2024-04-23 17:06:28 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,如何从对象数组中移除对象?像这样:

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

我试过array.remove(),但它只对值起作用,而不是数组中的特定位置。我需要能够通过定位对象的位置来删除它(remove array[0]


Tags: 对象定位object数组arrayremove对值
3条回答
del array[0]

其中0list中对象的索引(python中没有数组)

如果要从列表中删除多个对象。有多种方法可以从列表中删除对象

试试这个代码。a是包含所有对象的列表,b是要删除的列表对象。

示例:

a = [1,2,3,4,5,6]
b = [2,3]

for i in b:
   if i in a:
      a.remove(i)

print(a)

输出是[1,4,5,6] 我希望,对你有用

在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

在您的情况下,要使用的适当方法是pop,因为它需要删除索引:

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

相关问题 更多 >