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

新手上路,请多包涵

在 Python 中,如何从对象列表中删除对象?像这样:

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

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

原文由 user1120190 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 678
1 个回答

有多种方法可以从列表中删除对象:

 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]

原文由 Ricardo Murillo 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题