python - 为什么我不能对相同的数据进行两次迭代?

标签 python iterator

为什么我不能在同一个 iterator 上迭代两次?

# data is an iterator.

for row in data:
    print("doing this one time")

for row in data:
    print("doing this two times")

这会打印 "doing this one time" 几次,因为 data 是非空的。但是,它打印“这样做两次”。为什么迭代 data 第一次有效,第二次无效?

最佳答案

这是因为 data 是一个迭代器,一个迭代器只能使用一次。例如:

lst = [1, 2, 3]
it = iter(lst)

next(it)
# => 1
next(it)
# => 2
next(it)
# => 3
next(it)
# => StopIteration

如果我们使用 for 循环遍历一些数据,最后一个 StopIteration 将导致它第一次退出。如果我们尝试再次对其进行迭代,我们将不断收到StopIteration异常,因为迭代器已被消耗。


现在是第二个问题:如果我们确实需要多次遍历迭代器怎么办?一个简单的解决方案是将所有元素保存到一个列表中,可以根据需要多次遍历该列表。例如,如果 data 是一个迭代器:

data = list(data)

只要列表中的元素很少就可以。但是,如果有很多元素,最好使用 tee() 创建独立的迭代器。 :

import itertools
it1, it2 = itertools.tee(data, 2) # create as many as needed

现在我们可以依次循环遍历每一个:

for e in it1:
    print("doing this one time")

for e in it2:
    print("doing this two times")

关于python - 为什么我不能对相同的数据进行两次迭代?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25336726/

相关文章:

Python sklearn 的带有分类箱的标签编码器

python - Pymel setColor 不适用于顶点

python - Pymongo 多处理

python - 可迭代,无副作用类型注释

c# - IEnumerator 或 IEnumerable 中的“产量”?

c++ - 最终迭代器递减的应用及其含义

python - 需要 matplotlib 中日期时间系列 3D 绘图的帮助

c++ - 为什么迭代器不依赖于分配器? (也就是说,让迭代器变得可怕不会违反分配器的 typedef 抽象吗?)

java - 为什么Java中的列表集合不使用new关键字创建迭代器对象

rust - 我可以使用在函数内部创建的值来扩展迭代器吗?