Python - keeping a counter inside a list
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 to share