python的迭代器坑_让python迭代器倒退?

Is there anyway to make a python list iterator to go backwards?

Basically i have this

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

I know why it gives me the output, however is there a way i can step backwards in the str() method, by one step?

EDIT

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?

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值