Home > Blockchain >  How do I count the last elements in a list after a certain element?
How do I count the last elements in a list after a certain element?

Time:07-30

I have a python list containing zeros and ones like this:

a = [1.0 1.0 0.0 0.0 1.0 0.0 1.0 0.0 0.0]

I know how to count the ones and zeros in this, but what I can't manage to figure out is how to count the last zeros after the last 1.0 in that list. In this case the solution would be "2". I would like to have a simple code which I can use for this problem in order to put it in a loop.

I hope someone can help me with that. Thank you!

CodePudding user response:

Try this:

a = [1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0]
a[::-1].index(1)

You reverse the list, and take the index of the first 1.

CodePudding user response:

An alternative using functional programming:

from itertools import takewhile
from operator import eq
from functools import partial

equal_0 = partial(eq, 0)

a = [1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0]

res = sum(1 for _ in takewhile(equal_0, reversed(a)))
print(res)

Output

2

CodePudding user response:

Another solution, if you want to use explicit for-loop:

a = [1.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0]

cnt = 0

for v in reversed(a):
    if v:
        break
    cnt  = 1

print(cnt)

Prints:

2
  • Related