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