枚举的实现细节是什么? [英] What is the implementation detail for enumerate?
问题描述
Python具有enumerate()
来遍历带有索引的对象.我怀疑解释器是否仅出于跟踪事物所在的目的而创建了许多int对象. PEP页面表示以下内容,但我不太了解发生了什么在引擎盖下:
Python has enumerate()
to iterate over objects with an index.I doubt that interpreters create a lot of int objects for the sole purpose of keeping track of where things are. The PEP page says the following, but I do not really understand what is going on under the hood:
它为所有可迭代对象提供与iteritems()提供给字典相同的优点-紧凑,可读,可靠的索引符号.
It provides all iterables with the same advantage that iteritems() affords to dictionaries -- a compact, readable, reliable index notation.
那这里的魔力是什么?
推荐答案
enumerate()
是迭代器;它只会动态产生索引int
值 ;它并不能完全产生它们.
enumerate()
is an iterator; it only produces the index int
value on the fly; it does not produce them all up front.
您可以尝试阅读 enumobject.c
源代码,但基本上可以像这样将其翻译成Python:
You can try to read the enumobject.c
source code, but it basically can be translated to Python like this:
def enumerate(iterable, start=0):
count = start
for elem in iterable:
yield count, elem
count += 1
yield
关键字使它成为生成器函数 ,您需要遍历生成器(或在生成器上调用next()
)以使该函数前进以生成数据,一次调用一次yield
.
The yield
keyword makes this a generator function, and you need to loop over the generator (or call next()
on it) to advance the function to produce data, one yield
call at a time.
Python还会实习int
值,介于-5和256(含)之间的所有值都是单例,因此上面的代码直到达到257时才产生新的int
对象.
Python also interns int
values, all values between -5 and 256 (inclusive) are singletons, so the above code doesn't even produce new int
objects until you reach 257.
这篇关于枚举的实现细节是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!