Python - keeping counter inside list comprehension

妖精的绣舞 提交于 2021-02-19 04:34:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!