Python-在列表理解中保持计数器 [英] Python - keeping counter inside list comprehension

查看:46
本文介绍了Python-在列表理解中保持计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以为以下循环编写列表理解?

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.

推荐答案

您可以使用 itertools.count :

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']

为避免tobias_k指出可能的ZeroDivisionError,您可以使用 enumerate(l,start = 1) 来使 enumerate 从1开始计数:

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']

这篇关于Python-在列表理解中保持计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆