I have a problem with splitting a nested list. There is an example of my input:
l = [[[35, 58, 'A'], [0, 18, 'B'], [76, 101, 'B'], [103, 130, 'A'], [134, 158, 'A']], [[2, 51, 'A'], [55, 115, 'B'], [125, 150, 'B']]]
I want to split it into two separate nested lists by the third element:
l_b = [[[0,18], [76,101]], [[55, 115], [125,150]]]
l_a = [[[35,58], [103, 130], [134,158]], [[2,51]]]
I tried to search by using a loop for:
for i in l:
for ii in i:
if ii[2] == 'A':
l_a.append(ii)
But I simply get a flat list, so I am losing the indexes.
Thanks in advance 😉
>Solution :
If you need to keep the nested structure for some reason:
l = [[[35, 58, 'A'], [0, 18, 'B'], [76, 101, 'B'], [103, 130, 'A'], [134, 158, 'A']], [[2, 51, 'A'], [55, 115, 'B'], [125, 150, 'B']]]
l_a = []
for i in l:
tmp_list = []
for ii in i:
if ii[2] == 'A':
tmp_list.append(ii[:2])
l_a.append(tmp_list)