4 回答
TA貢獻1877條經驗 獲得超6個贊
迭代法
__iter____getitem__IndexError
next__next__
formapnext
TA貢獻1942條經驗 獲得超3個贊
任何可以循環的東西(例如,您可以在字符串或文件上循環)或 可以出現在for-循環右側的任何內容: for x in iterable: ...或 任何你可以調用的東西 iter()它將返回一個ITERATOR: iter(obj)或 定義 __iter__返回一個新的ITERATOR,或者它可能有一個 __getitem__方法,適用于索引查找。
如果狀態記得它在迭代過程中所處的位置, 帶著 __next__方法: 返回迭代中的下一個值。 將狀態更新為指向下一個值。 發出信號時,它是通過提高 StopIteration這是可自我迭代的(意思是它有一個 __iter__方法返回 self).
這個 __next__方法在Python 3中是拼寫的。 next在Python 2中,以及 內建函數 next()調用傳遞給它的對象上的方法。
>>> s = 'cat' # s is an ITERABLE # s is a str object that is immutable # s has no state # s has a __getitem__() method >>> t = iter(s) # t is an ITERATOR # t has state (it starts by pointing at the "c" # t has a next() method and an __iter__() method>>> next(t) # the next() function returns the next value and advances the state'c'>>> next(t) # the next() function returns the next value and advances'a'>>> next(t) # the next() function returns the next value and advances't'>>> next(t) # next() raises StopIteration to signal that iteration is completeTraceback (most recent call last):... StopIteration>>> iter(t) is t # the iterator is self-iterable
TA貢獻1821條經驗 獲得超6個贊
迭代是具有__iter__()方法。它可能會重復多次,例如list()S和tuple()S.
迭代器是迭代的對象。由__iter__()方法,則通過自己的方法返回自身。__iter__()方法,并具有next()方法(__next__()(見3.x)。
迭代是調用以下內容的過程next()RESP.__next__()直到它升起StopIteration.
例子:
>>> a = [1, 2, 3] # iterable
>>> b1 = iter(a) # iterator 1
>>> b2 = iter(a) # iterator 2, independent of b1
>>> next(b1)
1
>>> next(b1)
2
>>> next(b2) # start over, as it is the first call to b2
1
>>> next(b1)
3
>>> next(b1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
>>> b1 = iter(a) # new one, start over
>>> next(b1)
1
添加回答
舉報
