简体   繁体   English

Python-如何删除列表列表中的最后一个元素?

[英]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]将获得的最后一个元素listadrlistadr[-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.

相关问题 Python-如何按另一个列表列表的最后一个元素对列表列表进行排序? - Python - How to sort a list of lists by last element of another list of lists? 如何根据python中的最后一个元素找到列表列表中的前3个列表? - How to find the top 3 lists in a list of list based on the last element in python? Python - 获取列表列表中每个列表的最后一个元素 - Python - get the last element of each list in a list of lists 删除列表中元组的元素 [Python, Tuples, Lists] - delete an element of a tuple within a list [Python, Tuples, Lists] 如何在列表的组合列表中删除列表的特定元素? - How can I delete a specific element of a list in a combined list of lists? 如何检查列表列表中是否存在元素 - how to check if an element exists in a list of lists python 如何有效地检查元素是否在 python 的列表列表中 - How to efficiently check if an element is in a list of lists in python Python:如果列表中的第一个元素重复并且第二个元素在列表系列中最低,则删除列表中的列表 - Python: delete list in list if 1st element in list is duplicated and 2nd element is lowest in lists series 如何从python中的列表中删除列表元素? - How to delete a list element from a list in python? 如何访问包含列表作为值的字典中列表值中的最后一个元素 - How to access the last element in the list values in a dictionary that contain lists as values
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM