If I have a list
JavaScript
x
2
1
x=[0.0,0.0,2.0,3.0,0.0,2.0]
2
and I basically want to count the amount of items in the list but only start after the leading zeroes, how would I do that? Keep in mind that I want to count the zero in the middle of the list but not the ones at the beginning.
I’ve tried this:
JavaScript
1
7
1
n=0
2
for i in x:
3
while i==0.0:
4
break
5
if i!=0.0:
6
n=n+1
7
But it didn’t get 4, which is the output I want as I want to include 2.0,3.0,0.0,2.0 only.
Advertisement
Answer
You can simply wrap your counter code in a conditional, with something like this:
JavaScript
1
11
11
1
x=[0.0,0.0,2.0,3.0,0.0,2.0]
2
start_counting = False
3
item_count = 0
4
5
for i in x:
6
if i != 0.0:
7
start_counting = True
8
if start_counting:
9
item_count += 1
10
11
item_count
will now have the amount of items in the list without the starting 0.0s