计算生成器/迭代器中项目数的最短方法是什么? [英] What's the shortest way to count the number of items in a generator/iterator?

查看:137
本文介绍了计算生成器/迭代器中项目数的最短方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想要迭代中的项目数而不关心元素本身,那么获得该元素的pythonic方法是什么?现在,我要定义

If I want the number of items in an iterable without caring about the elements themselves, what would be the pythonic way to get that? Right now, I would define

def ilen(it):
    return sum(itertools.imap(lambda _: 1, it))    # or just map in Python 3

但我理解 lambda 接近被认为是有害的, lambda _:1 肯定不是很漂亮。

but I understand lambda is close to being considered harmful, and lambda _: 1 certainly isn't pretty.

(这个用例是计算匹配正则表达式的文本文件中的行数,即 grep -c 。)

(The use case of this is counting the number of lines in a text file matching a regex, i.e. grep -c.)

推荐答案

通常的方式是

sum(1 for i in it)

这篇关于计算生成器/迭代器中项目数的最短方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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