I am trying to split a list based on binary condition
Question:
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]]
Answers:
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]]
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]]
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]]