亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

迭代器、迭代器和迭代到底是什么?

迭代器、迭代器和迭代到底是什么?

MYYA 2019-06-01 16:05:43
迭代器、迭代器和迭代到底是什么?Python中“迭代”、“迭代器”和“迭代”的最基本定義是什么?我已經閱讀了多個定義,但我無法確定確切的含義,因為它仍然不會沉入其中。有誰能幫我解決這三個外行術語的定義嗎?
查看完整描述

4 回答

?
慕哥9229398

TA貢獻1877條經驗 獲得超6個贊

迭代法是一個籠統的術語,用來指一個接一個地拿走一件的每一件東西。每當您使用一個循環(顯式或隱式)遍歷一組項時,即迭代。

在Python里,可迭代迭代器有特定的含義。

可迭代是具有__iter__方法返回迭代器,或者定義__getitem__方法,該方法可以從零開始接受順序索引(并引發IndexError當索引不再有效時)。所以可迭代是一個可以獲得迭代器從…。

迭代器是具有next(Python 2)或__next__(Python 3)方法。

無論何時使用for循環,或map,或列表理解等。在Python中,next方法自動調用,以從迭代器,從而經歷了…的過程。迭代法.

一個開始學習的好地方是本教程的迭代器部分標準類型頁的迭代器類型部分..在您了解了基本知識之后,嘗試函數編程方法的迭代器部分.


查看完整回答
反對 回復 2019-06-01
?
手掌心

TA貢獻1942條經驗 獲得超3個贊

下面是我在教學Python課程時使用的解釋:

ITERABLE是:

  • 任何可以循環的東西(例如,您可以在字符串或文件上循環)或
  • 可以出現在for-循環右側的任何內容:

    for x in iterable: ...

  • 任何你可以調用的東西

    iter()

    它將返回一個ITERATOR:

    iter(obj)

  • 定義

    __iter__

    返回一個新的ITERATOR,或者它可能有一個

    __getitem__

    方法,適用于索引查找。

ITERATOR是一個對象:

  • 如果狀態記得它在迭代過程中所處的位置,
  • 帶著

    __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


查看完整回答
反對 回復 2019-06-01
?
達令說

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


查看完整回答
反對 回復 2019-06-01
  • 4 回答
  • 0 關注
  • 2231 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號