发电机输出长度 [英] Length of generator output
问题描述
Python提供了一种很好的方法来获取渴望的可迭代的长度,即len(x)
.但是对于以生成器理解和函数表示的惰性可迭代对象,我找不到任何类似的东西.当然,写这样的东西并不难:
Python provides a nice method for getting length of an eager iterable, len(x)
that is. But I couldn't find anything similar for lazy iterables represented by generator comprehensions and functions. Of course, it is not hard to write something like:
def iterlen(x):
n = 0
try:
while True:
next(x)
n += 1
except StopIteration: pass
return n
但是我无法摆脱正在重新使用自行车的感觉.
But I can't get rid of a feeling that I'm reimplementing a bicycle.
(当我键入该函数时,我想到了一个想法:也许确实没有这样的函数,因为它破坏了"它的论点.不过,对于我的情况来说这不是问题).
(While I was typing the function, a thought struck my mind: maybe there really is no such function, because it "destroys" its argument. Not an issue for my case, though).
P.S .:关于第一个答案-是的,类似len(list(x))
的方法也可以使用,但是会大大增加内存的使用量.
P.S.: concerning the first answers - yes, something like len(list(x))
would work too, but that drastically increases the usage of memory.
P.P.S .:重新检查...忽略P.S.,似乎我在尝试时出错,它可以正常工作.对不起,麻烦了.
P.P.S.: re-checked... Disregard the P.S., seems I made a mistake while trying that, it works fine. Sorry for the trouble.
推荐答案
没有一个是因为在一般情况下您不能这样做-如果您有一个惰性无限生成器怎么办?例如:
There isn't one because you can't do it in the general case - what if you have a lazy infinite generator? For example:
def fib():
a, b = 0, 1
while True:
a, b = b, a + b
yield a
这永远不会终止,但会生成斐波那契数.您可以通过调用next()
获得任意数量的斐波那契数.
This never terminates but will generate the Fibonacci numbers. You can get as many Fibonacci numbers as you want by calling next()
.
如果您真的需要知道项的数量,那么无论如何都无法一次线性地遍历它们,因此只能使用常规列表之类的不同数据结构.
If you really need to know the number of items there are, then you can't iterate through them linearly one time anyway, so just use a different data structure such as a regular list.
这篇关于发电机输出长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!