问题描述
Python生成器非常有用.与返回列表的函数相比,它们具有优势.但是,您可以len(list_returning_function())
.有没有办法len(generator_function())
?
Python generators are very useful. They have advantages over functions that return lists. However, you could len(list_returning_function())
. Is there a way to len(generator_function())
?
更新:
当然len(list(generator_function()))
可以工作.....
我正在尝试使用自己在正在创建的新生成器中创建的生成器.作为新生成器中计算的一部分,它需要知道旧生成器的长度.但是,我想将它们和生成器的属性保持在一起,特别是-不要将整个列表保存在内存中,因为它可能非常很长.
UPDATE:
Of course len(list(generator_function()))
would work.....
I'm trying to use a generator I've created inside a new generator I'm creating. As part of the calculation in the new generator it needs to know the length of the old one. However I would like to keep both of them together with the same properties as a generator, specifically - not maintain the entire list in memory as it may be very long.
更新2:
假设生成器知道,即使从第一步开始,它就是目标长度.另外,没有理由维持len()
语法.示例-如果Python中的函数是对象,那么我不能将长度分配给该对象的变量,新生成器可以访问该变量吗?
UPDATE 2:
Assume the generator knows it's target length even from the first step. Also, there's no reason to maintain the len()
syntax. Example - if functions in Python are objects, couldn't I assign the length to a variable of this object that would be accessible to the new generator?
推荐答案
生成器没有长度,毕竟不是集合.
Generators have no length, they aren't collections after all.
生成器是具有内部状态的函数(和精美的语法).您可以反复调用它们以获取值的序列,因此可以在循环中使用它们.但是它们不包含任何元素,因此要求生成器的长度就像要求函数的长度一样.
Generators are functions with a internal state (and fancy syntax). You can repeatedly call them to get a sequence of values, so you can use them in loop. But they don't contain any elements, so asking for the length of a generator is like asking for the length of a function.
函数是对象,但是不能为它们分配新的属性.原因可能是使这样的基本对象尽可能高效.
Functions are objects, but you cannot assign new attributes to them. The reason is probably to keep such a basic object as efficient as possible.
不过,您可以从函数中简单地返回(generator, length)
对,或者将生成器包装在一个简单的对象中,如下所示:
You can however simply return (generator, length)
pairs from your functions or wrap the generator in a simple object like this:
class GeneratorLen(object):
def __init__(self, gen, length):
self.gen = gen
self.length = length
def __len__(self):
return self.length
def __iter__(self):
return self.gen
g = some_generator()
h = GeneratorLen(g, 1)
print len(h), list(h)
这篇关于如何len(generator())的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!