user2297037
user2297037

Reputation: 1217

Python - keeping counter inside list comprehension

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

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

I do not know how to increment the counter inside the list comprehension.

Upvotes: 5

Views: 4369

Answers (1)

unutbu
unutbu

Reputation: 879411

You could use an 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 pointed out by tobias_k, you could make enumerate start counting from 1 by using enumerate(l, start=1):

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

Upvotes: 11

Related Questions