如何从列表列表中的列表中提取最后一项? (Python)
How to extract the last item from a list in a list of lists? (Python)
我有一个列表列表,想提取最后的项目并将它们放在列表列表中。提取最后一项相对容易。但是我所有的尝试都会产生一个列表,而不是列表列表。有什么建议吗?
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, 17, 17], [18, 17]]
例如我试过的是这个函数:
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, 18]]
作为结果有什么建议吗?
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)
打印:
[[15, 14, 15, 17, 17], [18, 17]]
我建议循环遍历列表两次,如下所示:
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)
我有一个列表列表,想提取最后的项目并将它们放在列表列表中。提取最后一项相对容易。但是我所有的尝试都会产生一个列表,而不是列表列表。有什么建议吗?
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, 17, 17], [18, 17]]
例如我试过的是这个函数:
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, 18]]
作为结果有什么建议吗?
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)
打印:
[[15, 14, 15, 17, 17], [18, 17]]
我建议循环遍历列表两次,如下所示:
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)