Is there a way to remember the position in a python iterator?

后端 未结 2 1044
暗喜
暗喜 2021-01-11 17:15

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

2条回答
  •  我在风中等你
    2021-01-11 17:46

    You can use a generator to do this

    def get_next(iterator):
        for item in iterator:
            yield item
    
    my_list_iterator = get_next(my_list)
    
    for val in my_list_iterator:
        do_stuff(val)
        if some_condition:
            break
    
    do_stuff()
    
    for val in my_list_iterator:
        continue_doing_stuff(val)
    

提交回复
热议问题