Extracting first and last element from sublists in nested list

谁说我不能喝 提交于 2021-02-07 08:43:48

问题


How do you extract the first and last elements from each sublist in a nested list?

For example:

x=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(x)
#[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

The desired result-

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

Output:

>>> a
[[1, 3], [4, 6], [7, 9]]



回答2:


Here is how you can use list slices:

x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = [l[::len(l)-1] for l in x]
print(x)

Output:

[[1, 3], [4, 6], [7, 9]]



回答3:


x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

>>> [a[:1] + a[-1:] for a in x]
[[1, 3], [4, 6], [7, 9]]

I extract 2 slices, one with the first element, one with the last, and concatenate them.
It will works even when sublist are of different lengths.




回答4:


This works:


x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for item in x:
    print(item[0], item[2])

For your exact desired result, use this:


x = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
new_list = []
for item in x:
    new_list.append([item[0], item[2]])

print(new_list)




回答5:


I would recommend doing it like this. The list[-1] syntax is meant to get the last element in a list which is what you want.

x=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

for elem in x:
    print(elem[0], elem[-1])

This just prints them in a standard format but to put them back into a new list in this order would be simple.




回答6:


You can loop through the list and access them from there:

x=[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

out = []
for arr in x:
    out.append([arr[0], arr[-1]])

print(out)

Output:

[[1, 3], [4, 6], [7, 9]]

Furthermore, you can use list comprehension:

out = [[arr[0], arr[-1]] for arr in x]


来源:https://stackoverflow.com/questions/62822696/extracting-first-and-last-element-from-sublists-in-nested-list

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