pythonlist

Separating/Adding lists together for a 2D array


Firstly I want to say thank you in advance for any and all help it's small for some but big for others and you have my gratitude!

I have a list of numbers and need to analyze them in two different ways.
[[ 0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [ 0, 1, 1, 1, 0]]

Firstly I need to add up any 1's and group them but ONLY if they're after each other. For this example:
>>>[[1, 1], [5], [3]]
(if 0 then post a 0)

Then I need to add each row but one column at a time
[[ **0**, 1, 0, 1, 0], [**1**, 1, 1, 1, 1], [ **0**, 1, 1, 1, 0]]
>>>1
(Continues to the next column)
[[ 0, **1**, 0, 1, 0], [1, **1**, 1, 1, 1], [ 0, **1**, 1, 1, 0]]
>>>3
etc, etc.

Thanks again!


Solution

  • I don't know if I understood your question completely, but hopefully this could help:

    L = [[ 0, 1, 0, 1, 0], [1, 1, 1, 1, 1], [ 0, 1, 1, 1, 0]]
    
    def get_ones(l : list) -> list:
        res = []
        for sublist in l:
            ones = 0
            subres = []
            for item in sublist:
                if item == 1:
                    ones += 1
                else:
                    if ones > 0:
                        subres.append(ones)
                    ones = 0
            if ones > 0:
                subres.append(ones) # All were ones
            res.append(subres)
        return res
    
    def sum_column_ones(l : list, column) -> int:
        # assertion you have same amount of columns
        ones = 0
        for sublist in l:
            if sublist[column] == 1:
                ones += 1
        return ones
        
    print(get_ones(L))
    
    for i in range(len(L[0])): # iterate all columns
        print(f"Ones in column {i}: {sum_column_ones(L, i)}")
    
    
    [[1, 1], [5], [3]]
    Ones in column 0: 1
    Ones in column 1: 3
    Ones in column 2: 2
    Ones in column 3: 3
    Ones in column 4: 1