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. 回答1: 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