让python迭代器倒退?

Ube*_*per 25 python iterator list

反正有没有让python列表迭代器倒退?

基本上我有这个

class IterTest(object):
    def __init__(self, data):
        self.data = data
        self.__iter = None

    def all(self):
        self.__iter = iter(self.data)
        for each in self.__iter:
            mtd = getattr(self, type(each).__name__)
            mtd(each)

    def str(self, item):
        print item

        next = self.__iter.next()
        while isinstance(next, int):
            print next
            next = self.__iter.next()

    def int(self, item):
        print "Crap i skipped C"

if __name__ == '__main__':
    test = IterTest(['a', 1, 2,3,'c', 17])
    test.all()
Run Code Online (Sandbox Code Playgroud)

运行此代码会产生输出:

a
1
2
3
Crap i skipped C
Run Code Online (Sandbox Code Playgroud)

我知道为什么它给了我输出,但是有一种方法我可以在str()方法中向后退一步吗?

编辑

好吧也许可以让这个更清楚.我不想做完全反向,基本上我想知道是否有一种简单的方法在python中做相当于双向迭代器?

Tam*_*más 24

不,通常你不能让Python迭代器倒退.但是,如果您只想退一步,可以尝试这样的事情:

def str(self, item):
    print item

    prev, current = None, self.__iter.next()
    while isinstance(current, int):
        print current
        prev, current = current, self.__iter.next()
Run Code Online (Sandbox Code Playgroud)

然后,您可以随时访问上一个元素prev.

如果你真的需要一个双向迭代器,你可以自己实现一个,但它可能会比上面的解决方案引入更多的开销:

class bidirectional_iterator(object):
    def __init__(self, collection):
        self.collection = collection
        self.index = 0

    def next(self):
        try:
            result = self.collection[self.index]
            self.index += 1
        except IndexError:
            raise StopIteration
        return result

    def prev(self):
        self.index -= 1
        if self.index < 0:
            raise StopIteration
        return self.collection[self.index]

    def __iter__(self):
        return self
Run Code Online (Sandbox Code Playgroud)

  • @etuardu:你使用的是Python 3吗?iirc`next`已被重命名为`__next__`. (3认同)
  • 我上面添加了一个`bidirectional_iterator'示例,因为我已经看到你已经更新了你的问题,但这可能比我的第一个解决方案带来更多的开销. (2认同)
  • 奇怪的是,它适用于我(Python 2.7.1,Mac OS X).迭代器在Python中需要的所有AFAIK都是一个``next()``方法和一个返回自身的`__iter ___``. (2认同)

D.S*_*ley 7

我错过了什么或者你不能使用Python教程的Iterator部分中描述技术?

>>> class reverse_iterator:
...     def __init__(self, collection):
...         self.data = collection
...         self.index = len(self.data)
...     def __iter__(self):
...         return self
...     def next(self):
...         if self.index == 0:
...             raise StopIteration
...         self.index = self.index - 1
...         return self.data[self.index]
...     
>>> for each in reverse_iterator(['a', 1, 2, 3, 'c', 17]):
...     print each
... 
17
c
3
2
1
a
Run Code Online (Sandbox Code Playgroud)

我知道这不会向后移动迭代器,但我很确定通常没有办法做到这一点.相反,编写一个以相反顺序遍历离散集合的迭代器.

编辑你也可以使用该reversed()函数为任何集合获取反向迭代器,这样你就不必编写自己的:

>>> it = reversed(['a', 1, 2, 3, 'c', 17])
>>> type(it)
<type 'listreverseiterator'>
>>> for each in it:
...  print each
... 
17
c
3
2
1
a
Run Code Online (Sandbox Code Playgroud)

  • 我不想反转整个迭代器我在python中寻找等价的双向迭代器. (2认同)