1

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

1
  • Your example is not clear, you are saying "terator who are greater than the element before and after it." what is the element that u r calculating based on it, the elemnt before/after it. Commented Nov 4, 2014 at 23:58

3 Answers 3

3

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]
Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

How would I get the next element and previous element without calling next()?
0

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]

1 Comment

The problem is I can't make x a list. X is an iterator. next(x)=0, next(x)=1, next(x)=-1, next(x)=3.... Also for the head and tail, they would just consider one side of them, the end side would be always true.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.