简体   繁体   中英

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']]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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