How to slice a generator object or iterator?

后端 未结 4 733
小鲜肉
小鲜肉 2020-12-03 11:04

I would like to loop over a \"slice\" of an iterator. I\'m not sure if this is possible as I understand that it is not possible to slice an iterator. What I would like to do

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 11:34

    You can't slice a generator object or iterator using a normal slice operations. Instead you need to use itertools.islice as @jonrsharpe already mentioned in his comment.

    import itertools    
    
    for i in itertools.islice(x, 95)
        print(i)
    

    Also note that islice returns an iterator and consume data on the iterator or generator. So you will need to convert you data to list or create a new generator object if you need to go back and do something or use the little known itertools.tee to create a copy of your generator.

    from itertools import tee
    
    
    first, second = tee(f())
    

提交回复
热议问题