2015-07-12 25 views
-1

我在閱讀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

想知道爲什麼你應該使用一個迭代器?鍵入'範圍(10 ** 12)'到python 2解釋器中:P – NightShadeQueen

+0

是的,通過簡單的例子,您將看到很少的區別。但是大的(甚至是* infinite *),這是完全可能的:'def demo():while True:yield True')迭代器? – jonrsharpe

+0

當你想要閱讀一個巨大的文件時,它們也很有用,而不會造成計算機崩潰。 – NightShadeQueen

回答

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... 

OUTPUT:

1 
1 
2 
3 
5 
8 
13 
21