python迭代器都有哪些方法_有没有办法记住python迭代器中的位置?

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.

Something like:

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?

解决方案

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.

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)

shows:

a

b

taking a break

c

d

iter(obj) just returns the result of obj.__iter__(), which should be an iterator implementing a .__next__() method.

That __next__ method is called for each iteration, returning the object (in this case, a character.)

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))

prints:

a

b

taking a break

c

d

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值