问题
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
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']
来源:https://stackoverflow.com/questions/27778604/python-keeping-counter-inside-list-comprehension