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

I am trying to split a list based on binary condition

list [['0.jpg',0],['1.jpg',1],['2.jpg',1],['3.jpg',0],['4.jpg',1]]

I am trying to split it into two list

the output I am expecting to have is two list:

list_0 = [['0.jpg',0],['3.jpg',0]]
list_1 = [['1.jpg',1],['2.jpg',1],['4.jpg',1]]

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

>Solution :

It’s not appropriate you name your variable list because it’s a python built-in function:
What this code is doing is that, the for loops will loop the original list to see if the second item of every sub-list matches a condition then it should include that sub-list to a new list.

original_list = [['0.jpg',0],['1.jpg',1],['2.jpg',1],['3.jpg',0],['4.jpg',1]]

list_0 = [i for i in original_list if i[1] == 0]
list_1 = [i for i in original_list if i[1] == 1]

print(list_0)
print(list_1)


[['0.jpg', 0], ['3.jpg', 0]]
[['1.jpg', 1], ['2.jpg', 1], ['4.jpg', 1]]
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