"迭代器&#34 ;?的具体用例是什么?

时间:2015-07-12 16:24:26

标签: python

我正在阅读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>

1 个答案:

答案 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