从python中的对象列表中删除对象 [英] Remove object from a list of objects in python

查看:117
本文介绍了从python中的对象列表中删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Python, how can I remove an object from array of objects? Like this:

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

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

I've tried array.remove() but it only works with a value, not a specific location in the array. I need to be able to delete the object by addressing its position(remove array[0])

推荐答案

在 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]

这篇关于从python中的对象列表中删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆