Python Iterator: Reset Iterator?
Can you reset iterators? Or is there a way to save the next element without iterating through it?
Solution 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]
Solution 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.
Post a Comment for "Python Iterator: Reset Iterator?"