我正在阅读What exactly are Python's iterator, iterable, and iteration protocols?但为什么我们需要使用"迭代器" ?如下所示,我们可以使用带索引方法的简单list
:
s= 'cat'
print s[0]
print s[1]
print s[2]
print s[3]
C:\Users\test\Desktop>python iterator.py
c
a
t
Traceback (most recent call last):
File "iterator.py", line 9, in <module>
print s[3]
IndexError: string index out of range
C:\Users\test\Desktop>
s = 'cat'
t = iter(s)
print next(t)
print next(t)
print next(t)
print next(t)
C:\Users\test\Desktop>python iterator.py
c
a
t
Traceback (most recent call last):
File "iterator.py", line 36, in <module>
print next(t)
StopIteration
C:\Users\test\Desktop>
答案 0 :(得分:1)
在您的示例中,使用可迭代和直接访问字符串对象之间没有太大区别。
Iterable是行为的更高抽象。例如,它可以是仅在调用函数时懒惰地评估next()
项的对象。示例:
class Fibonacci(object):
def __init__(self):
self.x = 1
self.y = 1
def next(self):
tmp = self.x
self.x = self.y
self.y = self.y + tmp
return tmp
if "__main__" == __name__:
fib = Fibonacci()
print fib.next()
print fib.next()
print fib.next()
print fib.next()
print fib.next()
print fib.next()
print fib.next()
print fib.next()
# ... and we can go like this for a long time...
<强>输出:强>
1
1
2
3
5
8
13
21