你能重置迭代器吗?或者,有没有一种方法可以保存下一个元素,而不需要迭代它?
发布于 2014-11-05 08:15:53
您可以使用itertools.tee
来“记住”迭代器的先前值
>>> 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]
发布于 2014-11-05 08:07:04
我想到了在两个独立的变量中保留最后两个元素的一个小缓冲区,元组,列表等,并与迭代器中的当前元素进行比较。
发布于 2014-11-05 08:07:13
通过排除元素处于边缘(头部、尾部)的情况,我们通过将每个元素与前置/后继进行比较来遍历该元素,如果它正在验证条件,则将其添加到列表中。
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]
更新
在本例中,我们将使用while
循环到iter中,每次我们将数据存储到三个变量left,middle,right中。每当我们调用下一个变量时,我们从中间向左移动,从最后移动到中间,并将下一个新值存储在最后。
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]
https://stackoverflow.com/questions/26747296
复制相似问题