Python: Removing a single element from a nested list

两盒软妹~` 提交于 2021-01-27 06:34:35

问题


I'm having trouble figuring out how to remove something from within a nested list.

For example, how would I remove 'x' from the below list?

lst = [['x',6,5,4],[4,5,6]]

I tried del lst[0][0], but I get the following result:

TypeError: 'str' object doesn't support item deletion.

I also tried a for loop, but got the same error:

for char in lst:
    del char[0]

回答1:


Your code works fine. Are you sure lst is defined as [['x',6,5,4],[4,5,6]]? Because if it is, del lst[0][0] effectively deletes 'x'.

Perhaps you have defined lst as ['x',6,5,4], in which case, you will indeed get the error you are mentioning.




回答2:


Use the pop(i) function on the nested list. For example:

lst = [['x',6,5,4],[4,5,6]]
lst[0].pop(0)
print lst  #should print [[6, 5, 4], [4, 5, 6]]

Done.




回答3:


You can also use "pop". E.g.,

list = [['x',6,5,4],[4,5,6]]
list[0].pop(0)

will result in

list = [[6,5,4],[4,5,6]]

See this thread for more: How to remove an element from a list by index in Python?



来源:https://stackoverflow.com/questions/5292573/python-removing-a-single-element-from-a-nested-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!