在Python中使用next()的迭代中,如何返回到初始值?

问题描述 投票:0回答:1

我正在自己学习Python。

我遇到过以下内容

sol=map(pow,[1,2,3],[4,5,6])

sol是一个迭代器。

当我连续运行next(sol)时,将迭代sol的元素,直到出现StopIteration错误。

但是,如何重新启动迭代?

我已经尝试过iter_1=itertools.cycle(sol),但是我需要通过运行sol并随后只有sol=map(pow,[1,2,3],[4,5,6])来重新启动iter_1=itertools.cycle(sol)

还有其他方法吗?

python python-3.x iterator
1个回答
1
投票

迭代迭代器/生成器会消耗其中的值(无限生成器是一个例外),这意味着它们在以后的迭代中将不再可用(如您所见)。对于Python中的典型迭代器/生成器,“重新启动”的唯一正确方法是重新初始化它。

>>> sol = map(pow, [1, 2, 3], [4, 5, 6])      
>>> list(sol)
[1, 32, 729]
>>> next(sol)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration
>>> sol = map(pow, [1, 2, 3], [4, 5, 6])
>>> next(sol)
1

但是,您可以使用迭代器使其可重用,例如使用itertools.tee(如@JanChristophTerasa所链接的问题的答案之一所述),或将迭代器转换为列表,将保留其数据。

itertools.tee

itertools.tee

尽管使用>>> from itertools import tee >>> sol = map(pow, [1, 2, 3], [4, 5, 6]) >>> a, b = tee(sol, 2) >>> list(a) [1, 32, 729] >>> list(b) [1, 32, 729] >>> list(a) [] ,但teea仍将是迭代器,因此它们将遇到相同的问题。

另一种解决此问题的常用方法是使用b

list()

现在,sol = list(map(pow, [1, 2, 3], [4, 5, 6])) >>> sol [1, 32, 729] >>> sol [1, 32, 729] 是值列表,而不是迭代器,这意味着您可以根据需要对其进行多次迭代-值将保留在那里。这[[does表示您不能将sol与它一起使用(在next的意义上),但是如果您特别需要迭代器,则可以使用next(sol)从新列表中返回一个迭代器。 >

© www.soinside.com 2019 - 2024. All rights reserved.