从嵌套列表的子列表中提取第一个和最后一个元素 [英] Extracting first and last element from sublists in nested list
本文介绍了从嵌套列表的子列表中提取第一个和最后一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从嵌套列表中的每个子列表中提取第一个和最后一个元素?
How do you extract the first and last elements from each sublist in a nested list?
例如:
x=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(x)
#[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
期望的结果-
[[1, 3], [4, 6], [7, 9]]
这是我见过的最接近的地方-
This is the closest I've seen-
a = [x[i][i] for i in (0, -1)]
print(a)
#[1, 9]
推荐答案
您有正确的想法.如果列表中的列表仅深一层,则可以像尝试尝试的那样使用列表理解和-1索引访问第一个和最后一个元素:
You have the right idea. If your list inside list is only one layer deep, you can access the first and last elements with a list comprehension and -1 indexing like you were trying to do:
a = [[sublist[0],sublist[-1]] for sublist in x]
输出:
>>> a
[[1, 3], [4, 6], [7, 9]]
这篇关于从嵌套列表的子列表中提取第一个和最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文