问题描述
我想遍历一个可迭代的对象(比如说一个列表),并在某个时候记住我离开的位置以便下次调用该对象的迭代器时继续.
I would like to iterate over an iterable object (let's say, a list) and leave at some point remembering the position where I left off to continue the next time an iterator for that object is called.
类似的东西:
for val in list:
do_stuff(val)
if some_condition:
break
do_stuff()
for val in list:
continue_doing_stuff(val)
速度很重要,所考虑的清单很大.因此,保存对象并再次遍历整个列表直到找到所保存的元素都不是一种选择.如果不为列表编写显式的迭代器类,这是否可能?
Speed matters and the list considered is quite large. So saving the object and iterating again through the whole list until the saved element is found is not an option. Is this possible without writing an explicit iterator class for the list?
推荐答案
当您使用对象输入for循环并返回迭代器时,将调用__iter__
方法.通常,我们不保留指向迭代器的名称,但是如果这样做,我们可以停止迭代,执行其他操作,然后继续进行迭代.
The __iter__
method is called when you enter a for loop with an object, returning an iterator. We usually don't keep a name pointing to the iterator, but if we do, we can stop the iterating, do something else, and then resume the iterating.
获取迭代器对象的最佳方法是使用内置的iter
函数:
The best way to get the iterator object is to use the builtin iter
function:
a_list = ['a', 'b', 'c', 'd']
iter_list = iter(a_list)
for val in iter_list:
print(val) # do_stuff(val)
if val == 'b': # some_condition!
break
print('taking a break') # do_stuff()
for val in iter_list:
print(val) # continue_doing_stuff(val)
显示:
a
b
taking a break
c
d
iter(obj)
仅返回obj.__iter__()
的结果,该结果应该是实现.__next__()
方法的迭代器.
iter(obj)
just returns the result of obj.__iter__()
, which should be an iterator implementing a .__next__()
method.
每次迭代都会调用__next__
方法,并返回对象(在这种情况下为字符).
That __next__
method is called for each iteration, returning the object (in this case, a character.)
如果要自己调用__next__
方法而不是由for循环调用它,则应使用内置的next
函数:
If you want to call the __next__
method yourself instead of having it called by the for loop, you should use the builtin next
function:
a_list = ['a', 'b', 'c', 'd']
iter_list = iter(a_list)
print(next(iter_list)) # do_stuff(val)
print(next(iter_list))
print('taking a break') # do_stuff()
print(next(iter_list)) # continue_doing_stuff(val)
print(next(iter_list))
打印:
a
b
taking a break
c
d
这篇关于有没有办法记住python迭代器中的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!