[英]Python - How to delete the last element in a list of lists?
I have a list of lists like this: 我有一个这样的清单清单:
listadr = [[a, b], [1, 2]]
How to remove the last entry of the last list to have this result ? 如何删除最后一个列表的最后一个条目以产生此结果?
result = [[a, b], [1]]
I have tried 我努力了
for adr in listadr:
for adr[1] in adr:
del adr[-1]
But this code delete also 'b' ... 但是这段代码也删除了'b'...
Delete only the last element's last element, like this 像这样仅删除最后一个元素的最后一个元素
listadr = [['a', 'b'], [1, 2]]
del listadr[-1][-1]
print(listadr)
# [['a', 'b'], [1]]
listadr[-1]
will get the last element of listadr
and listadr[-1][-1]
will get the last element of the last element of listadr
and kill it with del
. listadr[-1]
将获得的最后一个元素listadr
和listadr[-1][-1]
将获得的最后一个元素的最后一个元素listadr
,并杀死它del
。
Alternatively, you can do 或者,您可以
listadr[-1] = listadr[-1][:-1]
This would be replacing the last element of listadr
with the last element of listadr
excluding its last element. 这将是替换的最后一个元素
listadr
与最后一个元素listadr
不包括其最后一个元素。 listadr[-1][:-1]
means get all the elements till the last element of the last element of listadr
. listadr[-1][:-1]
表示获取所有元素,直到listadr
的最后一个元素的最后一个元素。
There's no need to loop here, simply index the list using [-1][-1]
: 此处无需循环,只需使用
[-1][-1]
为列表建立索引:
>>> listadr = [['a', 'b'], [1, 2]]
>>> del listadr[-1][-1]
>>> listadr
[['a', 'b'], [1]]
If you want the item as well then use list.pop()
on last sublist: 如果还需要该项目,则在最后一个子列表上使用
list.pop()
:
>>> listadr = [['a', 'b'], [1, 2]]
>>> listadr[-1].pop()
2
>>> listadr
[['a', 'b'], [1]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.