简体   繁体   English

如何从列表列表中提取最后一个子列表?

[英]How to extract the last sub-list from a list of lists?

If I have a list of lists, how can I remove every element from each list, except for the last element?如果我有一个列表列表,如何从每个列表中删除每个元素,除了最后一个元素? (Keeping only the last element from each list and deleting all other elements before it) (只保留每个列表中的最后一个元素并删除它之前的所有其他元素)

If my list of lists looks like this:如果我的列表如下所示:

lst = [['Hello', 'World'], ['Hello', 'E', 'Planet'], ['Planet', 'World', 'Earth']]

I want my outputted list to look like this:我希望我的输出列表如下所示:

lst_new = [['World'], ['Planet'], ['Earth']]

So far, my code looks like this, but the problem I'm facing is that it is eliminating the last list entirely from the list of lists:到目前为止,我的代码看起来像这样,但我面临的问题是它正在从列表中完全消除最后一个列表:

lst_new = [x for x in lst if x != lst.remove(lst[len(lst)-1])]
print(lst_new)
#[['Hello', 'World'], ['Hello', 'E', 'Planet']]

Where am I going wrong?我哪里错了? Would appreciate any help - thanks!将不胜感激任何帮助 - 谢谢!

Just use simple indexing:只需使用简单的索引:

>>> lst_new = [ [x[-1]] for x in lst ]
>>> lst_new
[['World'], ['Planet'], ['Earth']]

You can use slicing:您可以使用切片:

lst = [['Hello', 'World'], ['Hello', 'E', 'Planet'], ['Planet', 'World', 'Earth']]

lst_new = [sublst[-1:] for sublst in lst]
print(lst_new) # [['World'], ['Planet'], ['Earth']]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM