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

标签 python list object

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

相关文章:

python - 查找导致异常的执行路径

java - 尝试将 Object 转换为 EMF EObject 时出现 ClassCastException?

c++ - 有没有一个工具可以绘制我的 C++ 类和方法的图形表示?

Python,如何使用文件中的行作为字典中的键,使用下一行作为值?

python - 如何将tensorflow placerholder变量转换为numpy数组?

python - 如何将字符串列表转换为整数列表 - 很多事情似乎不起作用

python - 在python中将基数为10的整数列表转换为基数为4的列表

c# - 无法获取 Uri 的文件路径

python - 弹出索引超出范围

javascript - JS或jQuery如何删除键值对