Python關鍵字yield的解釋(stackoverflow)

來源:互聯網
上載者:User

標籤:yield   python   產生器   

提問者的問題

Python關鍵字yield的作用是什嗎?用來幹什麼的?

比如,我正在試圖理解下面的代碼:

def node._get_child_candidates(self, distance, min_dist, max_dist):    if self._leftchild and distance - max_dist < self._median:        yield self._leftchild    if self._rightchild and distance + max_dist >= self._median:        yield self._rightchild

下面的是調用:

result, candidates = list(), [self]while candidates:    node = candidates.pop()    distance = node._get_dist(obj)    if distance <= max_dist and distance >= min_dist:        result.extend(node._values)    candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))return result

當調用 _get_child_candidates 的時候發生了什嗎?返回了一個鏈表?返回了一個元素?被重複調用了嗎? 什麼時候這個調用結束呢?

回答部分

為了理解什麼是 yield,你必須理解什麼是產生器。在理解產生器之前,讓我們先走近迭代。

可迭代對象

當你建立了一個列表,你可以逐項地讀取這個列表,這叫做一個可迭代對象:

>>> mylist = [1, 2, 3]>>> for i in mylist :...    print(i)123

mylist 是一個可迭代的對象。當你使用一個列表產生式來建立一個列表的時候,就建立了一個可迭代的對象:

>>> mylist = [x*x for x in range(3)]>>> for i in mylist :...    print(i)014

所有你可以使用 for .. in .. 文法的叫做一個迭代器:鏈表,字串,檔案……你經常使用它們是因為你可以如你所願的讀取其中的元素,但是你把所有的值都儲存到了記憶體中,如果你有大量資料的話這個方式並不是你想要的。

產生器

產生器是可以迭代的,但是你 只可以讀取它一次 ,因為它並不把所有的值放在記憶體中,它是即時地產生資料:

>>> mygenerator = (x*x for x in range(3))>>> for i in mygenerator :...    print(i)014

看起來除了把 [] 換成 () 外沒什麼不同。但是,你不可以再次使用 for i in mygenerator , 因為產生器只能被迭代一次:先計算出0,然後繼續計算1,然後計算4,一個跟一個的…

yield關鍵字

yield 是一個類似 return 的關鍵字,只是這個函數返回的是個產生器。

>>> def createGenerator() :...    mylist = range(3)...    for i in mylist :...        yield i*i...>>> mygenerator = createGenerator() # create a generator>>> print(mygenerator) # mygenerator is an object!<generator object createGenerator at 0xb7555c34>>>> for i in mygenerator:...     print(i)014

這個例子沒什麼用途,但是它讓你知道,這個函數會返回一大批你只需要讀一次的值.

為了精通 yield ,你必須要理解:當你調用這個函數的時候,函數內部的代碼並不立馬執行 ,這個函數只是返回一個產生器對象,這有點蹊蹺不是嗎。

那麼,函數內的代碼什麼時候執行呢?當你使用for進行迭代的時候.

現在到了關鍵點了!

第一次迭代中你的函數會執行,從開始到達 yield 關鍵字,然後返回 yield 後的值作為第一次迭代的傳回值. 然後,每次執行這個函數都會繼續執行你在函數內部定義的那個迴圈的下一次,再返回那個值,直到沒有可以返回的。

如果產生器內部沒有定義 yield 關鍵字,那麼這個產生器被認為成空的。這種情況可能因為是迴圈進行沒了,或者是沒有滿足 if/else 條件。

回到你的代碼

(譯者注:這是回答者對問題的具體解釋)

產生器:

# Here you create the method of the node object that will return the generatordef node._get_child_candidates(self, distance, min_dist, max_dist):  # Here is the code that will be called each time you use the generator object :  # If there is still a child of the node object on its left  # AND if distance is ok, return the next child  if self._leftchild and distance - max_dist < self._median:            yield self._leftchild  # If there is still a child of the node object on its right  # AND if distance is ok, return the next child  if self._rightchild and distance + max_dist >= self._median:                yield self._rightchild  # If the function arrives here, the generator will be considered empty  # there is no more than two values : the left and the right children

調用者:

# Create an empty list and a list with the current object referenceresult, candidates = list(), [self]# Loop on candidates (they contain only one element at the beginning)while candidates:    # Get the last candidate and remove it from the list    node = candidates.pop()    # Get the distance between obj and the candidate    distance = node._get_dist(obj)    # If distance is ok, then you can fill the result    if distance <= max_dist and distance >= min_dist:        result.extend(node._values)    # Add the children of the candidate in the candidates list    # so the loop will keep running until it will have looked    # at all the children of the children of the children, etc. of the candidate    candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))return result

這個程式碼封裝含了幾個小部分:

  • 我們對一個鏈表進行迭代,但是迭代中鏈表還在不斷的擴充。它是一個迭代這些嵌套的資料的簡潔方式,即使這樣有點危險,因為可能導致無限迭代。 candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) 窮盡了產生器的所有值,但 while 不斷地在產生新的產生器,它們會產生和上一次不一樣的值,既然沒有作用到同一個節點上.
  • extend() 是一個迭代器方法,作用於迭代器,並把參數追加到迭代器的後面。
    通常我們傳給它一個鏈表參數:
>>> a = [1, 2]>>> b = [3, 4]>>> a.extend(b)>>> print(a)[1, 2, 3, 4]

但是在你的代碼中的是一個產生器,這是不錯的,因為:

你不必讀兩次所有的值
你可以有很多子物件,但不必叫他們都儲存在記憶體裡面。
並且這很奏效,因為Python不關心一個方法的參數是不是個鏈表。Python只希望它是個可以迭代的,所以這個參數可以是鏈表,元組,字串,產生器… 這叫做 duck typing,這也是為何Python如此棒的原因之一,但這已經是另外一個問題了…

你可以在這裡停下,來看看產生器的一些進階用法:

控制產生器的窮盡
>>> class Bank(): # let‘s create a bank, building ATMs...    crisis = False...    def create_atm(self) :...        while not self.crisis :...            yield "$100">>> hsbc = Bank() # when everything‘s ok the ATM gives you as much as you want>>> corner_street_atm = hsbc.create_atm()>>> print(corner_street_atm.next())$100>>> print(corner_street_atm.next())$100>>> print([corner_street_atm.next() for cash in range(5)])[‘$100‘, ‘$100‘, ‘$100‘, ‘$100‘, ‘$100‘]>>> hsbc.crisis = True # crisis is coming, no more money!>>> print(corner_street_atm.next())<type ‘exceptions.StopIteration‘>>>> wall_street_atm = hsbc.create_atm() # it‘s even true for new ATMs>>> print(wall_street_atm.next())<type ‘exceptions.StopIteration‘>>>> hsbc.crisis = False # trouble is, even post-crisis the ATM remains empty>>> print(corner_street_atm.next())<type ‘exceptions.StopIteration‘>>>> brand_new_atm = hsbc.create_atm() # build a new one to get back in business>>> for cash in brand_new_atm :...    print cash$100$100$100$100$100$100$100$100$100...

對於控制一些資源的訪問來說這很有用。

Itertools,你最好的朋友

itertools包含了很多特殊的迭代方法。是不是曾想過複製一個迭代器?串聯兩個迭代器?把嵌套的鏈表分組?不用創造一個新的鏈表的 zip/map?

只要 import itertools

需要個例子?讓我們看看比賽中4匹馬可能到達終點的先後順序的可能情況:

>>> horses = [1, 2, 3, 4]>>> races = itertools.permutations(horses)>>> print(races)<itertools.permutations object at 0xb754f1dc>>>> print(list(itertools.permutations(horses)))[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2), (1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]
瞭解迭代器的內部機理

迭代是一個實現可迭代對象(實現的是 __iter__() 方法)和迭代器(實現的是 __next__() 方法)的過程。可迭代對象是你可以從其擷取到一個迭代器的任一對象。迭代器是那些允許你迭代可迭代對象的對象。

更多見這個文章 http://effbot.org/zone/python-for-statement.htm

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Python關鍵字yield的解釋(stackoverflow)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.