How to extract the last item from a list in a list of lists? (Python)

試著忘記壹切 提交于 2021-01-29 08:31:21

问题


I have a list of lists and would like to extract the last items and place them in a lists of lists. It is relatively easy to extract the last items. But all my attempts result in one list, rather than in a list of lists. Any suggestions?

lst = [[[11, 12, 15], [12, 13, 14], [13, 14, 15], [14, 15, 17], [15, 16, 17]], [[14, 15, 18], [15, 16, 17]]]

The result I would like from this is: [[15, 14, 15, 17, 17], [18, 17]]

What I tried for example, is this function:

def Extract(lst): 
    for i in lst:
        return [item[-1] for item in i]
print(Extract(lst))

But this only gives: [15, 14, 15, 17, 17]

I also tried:

last = []
for i in lst:
    for d in i:
        last.append(d[-1])
last

But this gives: [15, 14, 15, 17, 17, 18, 17]

Any suggestions how to get [[15, 14, 15, 17, 17], [17, 18]] as the outcome?


回答1:


I would suggest looping through the list twice, like so:

lst = [[[11, 12, 15], [12, 13, 14], [13, 14, 15], [14, 15, 17], [15, 16, 17]], [[14, 15, 18], [15, 16, 17]]]

# Result of iteration
last_lst = []

# Iterate through lst
for item1 in lst:
    # Initialize temporary list
    last_item1 = []
    
    #Iterate through each list in lst
    for item2 in item1:
        # Add last item to temporary list
        last_item1.append(item2[-1])
        
    # Add the temporary list to last_lst
    last_lst.append(last_item1)



回答2:


lst = [[[11, 12, 15], [12, 13, 14], [13, 14, 15], [14, 15, 17], [15, 16, 17]], [[14, 15, 18], [15, 16, 17]]]

out = [[l[-1] for l in v] for v in lst]
print(out)

Prints:

[[15, 14, 15, 17, 17], [18, 17]]


来源:https://stackoverflow.com/questions/63199461/how-to-extract-the-last-item-from-a-list-in-a-list-of-lists-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!