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]]
Asked By: Steve



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]


[['0.jpg', 0], ['3.jpg', 0]]
[['1.jpg', 1], ['2.jpg', 1], ['4.jpg', 1]]
Answered By: Jamiu S.
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.