Python虫?懒惰的对象有隐藏的对象

2024-04-24 07:12:21 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑一下(Python3.3):

a=enumerate([2,3,5])
print(list(a))
print(list(a))

你真的希望两个打印调用打印不同的东西吗? 我也没有

如果用settupledict替换list,也会发生同样的情况。如果将enumerate对象替换为mapfilter,也会发生这种情况,但奇怪的是,如果将其替换为range,则不会发生这种情况。你知道吗

也许这是一个特征。但这是非常令人惊讶的,没有记录在案(至少我还没有找到任何关于它),而且不一致(范围不同)。你怎么认为?你知道吗


Tags: 对象map情况range特征filterdictlist
2条回答

enumerate()返回迭代器,其他调用也是如此。。您只能循环遍历迭代器一次;然后它就被耗尽了。你知道吗

您可以使用生成器函数自己创建这样的迭代器:

def somelist_generator():
    somelist = [1, 2, 3]
    while somelist:
        yield somelist.pop()

如果在somelist_generator()上循环,列表somelist将被清空。您只能这样做一次,因为.pop()会删除元素:

>>> it = somelist_generator()
>>> for i in it:
...     print(i)
... 
3
2
1
>>> next(it)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

next()调用尝试从it迭代器获取另一个值;它已经为空,因此引发了StopIteration异常。这个异常表示没有更多的元素可以获取,这就是为什么第二次尝试从迭代器获取任何内容时,最终会得到一个空列表:

>>> list(it)
[]

range()返回迭代器。它返回一个range object,它表示一个内存效率很高的数字序列;只需要存储开始、结束和步幅,其他所有内容都可以从这3个点派生出来。你知道吗

行为记录在http://docs.python.org/3/glossary.html#term-iterator

One notable exception is code which attempts multiple iteration passes. ... Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.

相关问题 更多 >