为什么len()不支持迭代器? [英] Why does len() not support iterators?
问题描述
许多Python的内置函数(例如any()
,all()
,sum()
等)都带有可迭代对象,但为什么len()
却没有呢?
Many of Python's built-in functions (any()
, all()
, sum()
to name some) take iterables but why does len()
not?
一个人总是可以将sum(1 for i in iterable)
用作等效项,但是为什么len()
首先不考虑可迭代项?
One could always use sum(1 for i in iterable)
as an equivalent, but why is it len()
does not take iterables in the first place?
推荐答案
许多可迭代对象是由生成器表达式定义的,这些生成器表达式的len定义不明确.采取以下措施,使其永远迭代:
Many iterables are defined by generator expressions which don't have a well defined len. Take the following which iterates forever:
def sequence(i=0):
while True:
i+=1
yield i
基本上,要有一个明确定义的长度,您需要预先了解整个对象.将该功能与sum
之类的功能进行对比.您无需一次了解整个对象就可以对其求和,只需一次获取一个元素并将其添加到已经求和的对象中即可.
Basically, to have a well defined length, you need to know the entire object up front. Contrast that to a function like sum
. You don't need to know the entire object at once to sum it -- Just take one element at a time and add it to what you've already summed.
请注意诸如sum(1 for i in iterable)
这样的惯用语,通常它会耗尽可迭代性,因此您将无法再使用它.或者,如果涉及大量计算,则获取第i个元素可能会很慢.可能值得自问,为什么需要知道先验长度.这可能使您对要使用哪种类型的数据结构有一定的了解(通常list
和tuple
可以正常工作)-或者您可以执行操作而无需调用len
.
Be careful with idioms like sum(1 for i in iterable)
, often it will just exhaust iterable so you can't use it anymore. Or, it could be slow to get the i'th element if there is a lot of computation involved. It might be worth asking yourself why you need to know the length a-priori. This might give you some insight into what type of data-structure to use (frequently list
and tuple
work just fine) -- or you may be able to perform your operation without needing calling len
.
这篇关于为什么len()不支持迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!