-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>
想知道爲什麼你應該使用一個迭代器?鍵入'範圍(10 ** 12)'到python 2解釋器中:P – NightShadeQueen
是的,通過簡單的例子,您將看到很少的區別。但是大的(甚至是* infinite *),這是完全可能的:'def demo():while True:yield True')迭代器? – jonrsharpe
當你想要閱讀一個巨大的文件時,它們也很有用,而不會造成計算機崩潰。 – NightShadeQueen