Home > Net >  Is there a way to only count number of nonzeo elements between zeros in a list?
Is there a way to only count number of nonzeo elements between zeros in a list?

Time:06-16

I am trying to count number of nonzero elements between zeros in a list.

This is my list

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

Desired output:

a = [1, 3, 2]

CodePudding user response:

You can use itertools.groupby:

from itertools import groupby

out = [len(list(g)) for k,g in groupby(a, lambda x: x!=0) if k]

output: [1, 3, 2]

how it works:

  • for each group of consecutive non-zero or zero item (lambda x: x!=0 sets the group key as True for non-zeros)
  • if the key is True, get the length of the group

CodePudding user response:

By using simple logic

a = [1, 0, 0, 0, 5, 6, 7, 0, 0, 2, 4, 0]
l=[]
c=0
for i in a:
    if i!=0:
        c=c 1
    else:
        if c!=0:
            l.append(c)
            c=0
print(l)

output :

[1, 3, 2]
  • Related