Home > database >  Is there a way to only remove zeros that are placed before the very first nonzero element of each su
Is there a way to only remove zeros that are placed before the very first nonzero element of each su

Time:05-12

I want to remove zeros that come before the very first nonzero element in each sublist

For example:

a = [[0, 0, 5, 2, 0, 3], [0, 1, 0, 5, 6], [0, 0, 0, 0, 4, 7, 9]]

Expected output:

a = [[5, 2, 0, 3], [1, 0, 5, 6], [4, 7, 9]]

I tried using index but it removed all zeros.

CodePudding user response:

A solution is to use numpy to find the index of the first non zero value in a sublist.

import numpy as np

a = [[0, 0, 5, 2, 0, 3], [0, 1, 0, 5, 6], [0, 0, 0, 0, 4, 7, 9]]
output = []

for b in a:
    c = np.array(b)
    start = b.index(c[c>0][0])
    output  = [b[start:]]
output

Then output is equal to [[5, 2, 0, 3], [1, 0, 5, 6], [4, 7, 9]]

CodePudding user response:

Built-in itertools module has dropwhile. So you can write code to drop elements while they are zero. dropwhile returns itertools.dropwhile object and if you need a list then you should convert into it using built-in list:

>>> from itertools import dropwhile
>>> a = [[0, 0, 5, 2, 0, 3], [0, 1, 0, 5, 6], [0, 0, 0, 0, 4, 7, 9]]
>>> [list(dropwhile(lambda x: x==0, item)) for item in a]
[[5, 2, 0, 3], [1, 0, 5, 6], [4, 7, 9]]
  • Related