Python - keeping a counter inside a list

Is it possible to write a list comprehension for the next loop?

m = []
counter = 0
for i, x in enumerate(l):
    if x.field == 'something':
        counter += 1
        m.append(counter / i)

      

I don't know how to increment a counter inside a list comprehension.

+3


source to share


1 answer


You can use itertools.count

:

import itertools as IT
counter = IT.count(1)
[next(counter)/i for i, x in enumerate(l) if x.field == 'something']

      



To avoid the possible ZeroDivisionError marked by tobias_k, you can do an initial count of enumerate

1 with enumerate(l, start=1)

:

[next(counter)/i for i, x in enumerate(l, start=1) 
 if x.field == 'something']

      

+9


source







All Articles