Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to split a nested list into two nested list by its element?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading