如何从列表列表中的列表中提取最后一项?(Python) [英] How to extract the last item from a list in a list of lists? (Python)
问题描述
我有一个列表列表,想提取最后一个项目并将它们放在列表列表中.提取最后一个项目相对容易.但是我所有的尝试都只产生一个列表,而不是一个列表.有什么建议吗?
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]]]
我想从中得到的结果是: [[15,14,15,15,17,17],[18,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))
但这仅给出: [15、14、15、17、17]
我也尝试过:
last = []
for i in lst:
for d in i:
last.append(d[-1])
last
但这给出了: [15、14、15、17、17、18、17]
有人建议如何获得 [[15,14,15,17,17,17],[17,18]]
作为结果吗?
Any suggestions how to get [[15, 14, 15, 17, 17], [17, 18]]
as the outcome?
推荐答案
我建议两次遍历列表,如下所示:
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)
这篇关于如何从列表列表中的列表中提取最后一项?(Python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!