2014-01-14 34 views
-1

我真的很新的python,我想要能夠做的就是從列表中刪除一些對象。基本上,列表體系結構是這樣的:對於每個列表對象,(?)中有5個自定義類對象,所以索引就像列表[0] [0]等。但是,我只能批量刪除像[[0 ],把所有的東西都帶走。這就是我剛剛玩弄它在命令行:如何從Python中的列表中刪除自定義類對象?

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

所以看起來它有事情做與自定義對象本身。我沒有自己定義這個班,所以我不知道發生了什麼。我怎樣才能在類定義中定義一些東西,以便我可以刪除單個對象?

+3

呃,你已經刪除它了。這不是例外。 –

+1

pop將彈出的元素返回,這就是爲什麼你不能做你想要的東西。 – Mattias

回答

2

流行返回的是列表中「不支持索引」的實際元素(簡而言之,返回的元素不是列表(實際上某個對象可以以這種方式訪問​​,但這是另一回事)) 。因此例外。

你可以做的是:

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] 

如果你沒有興趣再找個元素去掉,你可以簡單地使用德爾(假定指數存在):

del mylist[index] 

示例

>>> 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爲了不覆蓋list內置型。

+0

你應該添加一個嵌套列表的例子,因爲這似乎是他的實際用例;例如'mylist [0] .pop(1)' – l4mpi

+0

完美,非常感謝!我知道必須有一個簡單的解決方案,但是我很難找到它。 – isilya

相關問題