如何在python中从列表中删除自定义类对象?

如何在python中从列表中删除自定义类对象?,python,Python,我对python非常陌生,我只想从列表中删除一些对象。基本上,列表体系结构是这样的:对于每个列表对象,其中有5个自定义类对象,因此索引类似于列表[0][0],等等。但是,我只能批发删除类似列表[0]的内容,并将所有对象一起删除。这是我在命令行中玩的: >>> list.pop()[0][1] Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError

我对python非常陌生,我只想从列表中删除一些对象。基本上,列表体系结构是这样的:对于每个列表对象,其中有5个自定义类对象,因此索引类似于列表[0][0],等等。但是,我只能批发删除类似列表[0]的内容,并将所有对象一起删除。这是我在命令行中玩的:

>>> list.pop()[0][1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'nameless_class_to_protect_identity' object does not support indexing

因此,它似乎与自定义对象本身有关。我自己没有定义这个类,所以我真的不知道发生了什么。我如何在类定义中定义一些东西,以便删除单个对象?

pop返回的是列表中不支持索引的实际元素简言之,返回的元素不是列表事实上某些对象可以通过这种方式访问,但这是另一回事。因此有例外

您可以做的是:

mylist.pop(index) # this will remove the element at index-th position
范例

>>> mylist = [1, 2, 3, 4]
>>> mylist.pop(1)  # this will remove the element 2 of the list and return it
2  # returned element of the list
>>> print mylist
[1, 3, 4]
>>> mylist = [1, 2, 3, 4]
>>> del mylist[2]
>>> print mylist
[1, 2, 4]
如果您对删除元素不感兴趣,只要在索引存在的情况下使用del即可:

del mylist[index]
范例

>>> mylist = [1, 2, 3, 4]
>>> mylist.pop(1)  # this will remove the element 2 of the list and return it
2  # returned element of the list
>>> print mylist
[1, 3, 4]
>>> mylist = [1, 2, 3, 4]
>>> del mylist[2]
>>> print mylist
[1, 2, 4]
如果是嵌套列表:

>>> mylist = [[1, 2], ['a', 'b', 'c'], 5]
>>> mylist[0].pop(1)  # we pop the 2 element (element at index 1) of the list at index 0 of mylist
2
>>> print mylist
[[1], ['a', 'b', 'c'], 5]
>>> mylist.pop(1)[1]  # here we pop (remove) the element at index 1 (which is a list) and get the element 1 of that returned list
'b'
>>> print mylist  # mylist now possess only 2 elements 
[[1], 5]

在一个不相关的注释中,我调用了列表变量mylist而不是list,以避免覆盖列表内置类型。

Uh,您已经在删除它了。这不是异常的原因。pop返回popped元素,这就是为什么你不能做你正在尝试的事情。你应该为嵌套列表添加一个示例,因为这似乎是他的实际用例;e、 g.mylist[0].pop1Perfect,非常感谢!!!我知道必须有一个简单的解决办法,但我很难找到它。