【问题标题】:Python Iterator: reset iterator? [duplicate]Python 迭代器:重置迭代器? [复制]
【发布时间】:2015-01-01 01:26:57
【问题描述】:

你能重置迭代器吗?或者有没有办法在不迭代的情况下保存下一个元素?

【问题讨论】:

  • 您的示例不清楚,您是在说“大于前后元素的迭代器”。你基于它计算的元素是什么,它之前/之后的元素。

标签: python loops iterator iteration


【解决方案1】:

通过排除元素位于边缘(头、尾)的情况,我们通过将每个元素与前任/继任者进行比较来遍历该元素,如果它正在验证标准,我们将其添加到列表中。

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,并且每次我们将datat 存储到三个变量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]

【讨论】:

  • 问题是我不能让 x 成为一个列表。 X 是一个迭代器。 next(x)=0, next(x)=1, next(x)=-1, next(x)=3.... 同样对于头部和尾部,他们只会考虑它们的一侧,结束side 总是正确的。
【解决方案2】:

您可以使用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]

【讨论】:

    【解决方案3】:

    我想到将最后两个元素的小缓冲区保存在两个单独的变量中,一个元组,一个列表等,并与迭代器中的当前元素进行比较。

    【讨论】:

    • 如何在不调用 next() 的情况下获取下一个元素和上一个元素?
    猜你喜欢
    • 2015-06-09
    • 2018-05-24
    • 2012-03-23
    • 2018-02-06
    • 2018-08-19
    • 2018-04-26
    • 1970-01-01
    • 2020-05-18
    • 2017-07-05
    相关资源
    最近更新 更多