Python Iterator: reset iterator? [duplicate]

2019-07-27 11:35发布

问题:

This question already has an answer here:

  • Can iterators be reset in Python? 13 answers

Can you reset iterators? Or is there a way to save the next element without iterating through it?

回答1:

You can use itertools.tee to "remember" previous values of an iterator

>>> from itertools import tee, izip
>>> it = iter([0,1,-1,3,8,4,3,5,4,3,8])
>>> it1, it2, it3 = tee(it, 3)
>>> next(it2)
0
>>> next(it3)
0
>>> next(it3)
1
>>> [j for i, j, k in izip(it1, it2, it3) if i < j > k]
[1, 8, 5]


回答2:

It comes up to my mind to keep a small buffer of the last two elements in two separate variables, a tuple, a list, etc and compare with the current element in the iterator.



回答3:

By excluding cases where the element is in the edge (head, tail), we traverse the element by comparing every element to predecessor/successor, if it's verifying the criteria, we add it to the list.

x= [0,1,-1,3,8,4,3,5,4,3,8]

s= [ x[i] for i in xrange(1,len(x)-2) if x[i-1]< x[i] and x[i]> x[i+1] ]

print s  #Output: [1, 8, 5]

UPDATE

In this case, we would use while to loop into iter, and every time we store datat into three variable left, middle, right. Whenever we call the next variable, we shift middle to left, last to middle and store the next new value in last.

l= iter([0,1,-1,3,8,4,3,5,4,3,8])

res= []

left,middle,last= l.next(),l.next(),l.next() #Initialize data, we assume that we have at least 3 items, otherwise, we will get exception

while  True:
    try:
        if left<middle and middle>last: # I made first, to check in case we got that case in the first three items
            res+=[middle]
        left=middle
        middle= last
        last= l.next()
    except StopIteration:
        break

print res #Output: [1, 8, 5]