I have a problem where i have a list: list1 = [[0,0,0,1,0],[1,1,0,0,1]]
I want to separate the list into two different lists ones=[] and zeros=[]
except the values have to be separated corresponding to the initial list.
It would output this:
ones = [[1],[1,1,1]]
zeros = [[0,0,0,0],[0,0]]
How can this be done?
>Solution :
you need to iterate through the list, and on each list element/iterator, you need to calculate the no of times 1 and 0 occur, either by using list.count(value), or you can use a temporary lists which store the one and zero and once this inner list is done add that list to the main list
list1 = [[0,0,0,1,0],[1,1,0,0,1]]
ones =[ ]
zeros = []
for i in list1:
ones.append([1]*i.count(1))
zeros.append([0]*i.count(0))
or you can do
list1 = [[0,0,0,1,0],[1,1,0,0,1]]
ones =[ ]
zeros = []
for inner_list in list1:
tmp_zero , tmp_one = [], []
for val in inner_list:
if val==1:
tmp_one.append(val)
elif val==0:
tmp_zero.append(val)
ones.append(tmp_one)
zeros.append(tmp_zero)
print(ones)
print(zeros)
output
[[1], [1, 1, 1]]
[[0, 0, 0, 0], [0, 0]]