python - 计算迭代器的产量数?

标签 python python-3.x iterator

可以考虑一下功能

def f(iterator):
    count = 0
    for _ in iterator:
        count += 1
    return count

def g(iterator):
    return len(tuple(iterator))

相信它们唯一的不同之处是g可能会耗尽内存,而f则不会。
假设我是对的:

Is there a faster and/or otherwise-better (roughly, shorter without becoming code-golf) way to get f(iterator) while using less memory than tuple(iterator) takes up, preferably inline rather than as a function?

(如果fg有其他方式不同,那么我相信 fg 更有可能正确定义我所追求的功能。 我已经看过the itertools documentation page ,并且没有看到任何解决方案。)

最佳答案

您可以将 sum 与生成器表达式结合使用,为迭代器中的每个项目生成 1:

>>> it = (i for i in range(4))
>>> sum(1 for _ in it)
4

关于python - 计算迭代器的产量数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41339230/

相关文章:

python - django.db.utils.OperationalError : no such column: django_content_type. 名称?

python - 如何删除包含其绑定(bind)方法列表的对象

python - 在 for 循环中使用 *args 不考虑变化的变量

c++ - STL 列表迭代器不会更新我的对象

java - 集合与其迭代器之间是否存在循环依赖?

c++ - 无效使用非静态数据成员 'linkedList<int>::dummyNode' c++

python - Pandas df.idmax 在 0.22.0 版本中失败

python - Django 保存点回滚捕获完整性错误导致 TransactionManagementError

python-3.x - 在 pywin32 中创建一个新的 Excel 文件

python - Python简单绘图中这条线的方程是什么?