让python迭代器倒退? [英] Making a python iterator go backwards?
问题描述
有没有让python列表迭代器倒退?
Is there anyway to make a python list iterator to go backwards?
基本上我有这个
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()
运行此代码会产生输出:
Running this code results in the output:
a
1
2
3
Crap i skipped C
我知道为什么它给了我输出,但有一种方法我可以倒退str()方法,一步?
I know why it gives me the output, however is there a way i can step backwards in the str() method, by one step?
编辑
好吧也许使这更清楚。我不想做完全反向,基本上我想知道是否有一种简单的方法在python中做相当于双向迭代器?
Okay maybe to make this more clear. I don't want to do a full reverse, basically what i want to know if there is an easy way to do the equivalent of a bidirectional iterator in python?
推荐答案
不,通常你不能让Python迭代器倒退。但是,如果您只想退一步,可以尝试这样的事情:
No, in general you cannot make a Python iterator go backwards. However, if you only want to step back once, you can try something like this:
def str(self, item):
print item
prev, current = None, self.__iter.next()
while isinstance(current, int):
print current
prev, current = current, self.__iter.next()
然后您可以随时访问上一个元素在上一步
。
You can then access the previous element any time in prev
.
如果你真的需要一个双向迭代器,你可以自己实现一个,但它可能会介绍比上面的解决方案更开销:
If you really need a bidirectional iterator, you can implement one yourself, but it's likely to introduce even more overhead than the solution above:
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
这篇关于让python迭代器倒退?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!