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

Python list splitting and sorting with similar values

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?

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 :

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]]
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