Reputation: 169
I have a list of list of list and I would like to extract the n-th element from each sub-sub list. For example, given the following list:
my_list = [[[0, 0], [1, 1]], [[2, 0], [3, 2]], [[2, 0], [3, 3]], [[4, 0], [5, 4]], [[6, 0], [7, 5]]]
I want to extract all the first elements keeping the structure of the original list (list of list of list), like:
all_first_elements = [[[0],[1]], [[2],[3]], [[2],[3]], [[4],[5]], [[6],[7]]]
The problem is similar to this one but with one additional nested list.
I have tried all_first_elements = [item[0] for item in my_list]
but it returns the first elements of the list of list (and not the first elements of list of list of list).
Upvotes: 2
Views: 227
Reputation: 4315
The enumerate() function adds a counter to an iterable.
So for each element in a cursor, a tuple is produced with (counter, element)
.
my_list = [[[0, 0], [1, 1]], [[2, 0], [3, 2]], [[2, 0], [3, 3]], [[4, 0], [5, 4]], [[6, 0], [7, 5]]]
for sub_list in my_list:
for index,elm in enumerate(sub_list):
sub_list[index] = [elm[0]]
print(my_list)
O/P:
[[[0], [1]], [[2], [3]], [[2], [3]], [[4], [5]], [[6], [7]]]
Upvotes: 1
Reputation: 33
Here is a generic solution that you will not have to update if the nesting level changes:
def extract(data, level, index):
result = []
if level == 0:
return data[index]
for elem in data:
result.append(extract(elem, level-1, index))
return result
You will call it like this for the example provided in the original question:
print extract(my_list, level=2, index=0)
Please be aware that I have excluded data validation checks for the sake of clarity and because I was not sure how your data may vary. For example, the lists at the n-th level of depth may or may not be empty.
Upvotes: 0
Reputation: 18647
If you are open to using numpy
, you can slice and index using:
import numpy as np
np.array(my_list)[:, :, [0]]
[out]
array([[[0],
[1]],
[[2],
[3]],
[[2],
[3]],
[[4],
[5]],
[[6],
[7]]])
If you need the result as a list, just chain on the .tolist
method:
np.array(my_list)[:, :, [0]].tolist()
[out]
[[[0], [1]], [[2], [3]], [[2], [3]], [[4], [5]], [[6], [7]]]
Upvotes: 1
Reputation: 20490
You can use a double for loop within a list-comprehension
all_first_elements = [[[item_1[0]] for item_1 in item_0] for item_0 in my_list]
The output will be
[[[0], [1]], [[2], [3]], [[2], [3]], [[4], [5]], [[6], [7]]]
Upvotes: 3
Reputation: 6920
Try this :
all_first_elements = [[[i[0][0]],[i[1][0]]] for i in my_list]
Output :
[[[0], [1]], [[2], [3]], [[2], [3]], [[4], [5]], [[6], [7]]]
Upvotes: 0