Python学习iterator 迭代器小练习
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python学习iterator 迭代器小练习相关的知识,希望对你有一定的参考价值。
http://anandology.com/python-practice-book/iterators.html
Problem 1: Write an iterator class reverse_iter
, that takes a list and iterates it from the reverse direction. ::
>>> it = reverse_iter([1, 2, 3, 4])
>>> it.next()
4
>>> it.next()
3
>>> it.next()
2
>>> it.next()
1
>>> it.next()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
写了一个,倒是实现了,不知道是不是全世界效率最低的。
class reverse_iter:
"""docstring for ClassName"""
def __init__(self,target):
self.current = 0
self.target = target
self.len = len(target)
print self.len
def next(self):
if self.current < self.len:
self.current+=1
return self.target[self.len-self.current]
else:
raise StopIteration()
def __iter__(self):
return self
ri = reverse_iter([1,2,3,4])
print ri.next()
print ri.next()
print ri.next()
print ri.next()
print ri.next()
以上是关于Python学习iterator 迭代器小练习的主要内容,如果未能解决你的问题,请参考以下文章