python - 将迭代器转换为列表会更改迭代器

标签 python list iterator

下面的代码产生一些非常奇怪的结果

import re
string = "test test test"
positions = re.finditer("test", string)
print (list(positions))
print (list(positions))

输出:

[<Match object...>, <Match object...>, <Match object...>]
[]

现在,我想我知道这里发生了什么。第一个 list 调用“耗尽”迭代器(因此它“使用迭代器”,就像在生成器中一样,在从迭代器创建列表的过程中),所以当第二次调用 list 已创建,迭代器消失,我们得到一个空列表。下面的段落似乎证实了这一点,尽管我试图理解他们在这里所说的一些事情,所以我对这个解释并不完全满意(如果它是正确的):

A container object (such as a list) produces a fresh new iterator each time you pass it to the iter() function or use it in a for loop. 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.

以上段落来自the official documentation

我不太明白他们在上一段第一句话中所说的内容,特别是关于传递给 iter() 函数,而且我不知道他们如何连接使用一个 for 循环到一个列表,生成一个新的迭代器。不过,第二句话似乎更接近我最初想到的上面代码中发生的情况。

如果有人能帮助我消除这里的困惑,我将不胜感激。

注意:

我使用的是Python 3.5.1

最佳答案

这一行:

positions = re.finditer("test", string)

It returns a one-shot iterator 。然后,您在同一个迭代器上调用了 list(positions) 两次

所以第二次调用时,已经筋疲力尽了。

每次迭代列表时,列表都会为您提供一个新的迭代器,因此列表本身不会出现令人筋疲力尽的行为。比较以下行为以了解您引用的文档:

>>> L = ['a', 'b', 'c']
>>> list(L)
['a', 'b', 'c']
>>> list(L)
['a', 'b', 'c']
>>> iter_L = iter(L)  # calls L.__iter__() and returns you a one-shot iterator
>>> list(iter_L)
['a', 'b', 'c']
>>> list(iter_L)
[]

关于python - 将迭代器转换为列表会更改迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36094778/

相关文章:

java - 无接口(interface)方法stream()Ljava/util/stream/Stream;

java - 了解Iterator和Iterable接口(interface)的使用

Python positive-lookbehind 拆分可变宽度

python - gevent urllib 很慢

python - Altair:指定默认启用的渲染器

.net - 使用 LINQ 从列表创建元组列表

通过存储在列表 R 中的多个数据帧运行条件

c++ - for 中的迭代器无限循环列表

c++ - Hook std::list 中的对象。指针还是迭代器?

python - 对seaborn histplot 中的重叠条有一些指示