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?
CodePudding user response:
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]]
CodePudding user response:
try it:
ones = []
zeros = []
lists = [[0,0,0,1,0],[1,1,0,0,1]]
count = 0
for l in lists:
ones.append([])
zeros.append([])
for i in l:
if i: # i == 1
ones[count].append(i)
else: # i == 0
zeros[count].append(i)
count = 1
print(ones)
print(zeros)
CodePudding user response:
Here is a solution using a generator and collections.Counter
:
list1 = [[0,0,0,1,0],[1,1,0,0,1]]
from collections import Counter
counts = map(Counter, list1)
zeros, ones = map(list, zip(*([[i]*c[i] for i in (0,1)]
for c in counts)))
Output:
>>> zeros
[[0, 0, 0, 0], [0, 0]]
>>> ones
[[1], [1, 1, 1]]