Python關鍵字yield的解釋(stackoverflow)

(譯)Python關鍵字yield的解釋(stackoverflow)

譯者: hit9

原文: http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained

譯者注: 這是 stackoverflow 上一個很熱的帖子,這里是投票最高的一個答案

提問者的問題

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)
1
2
3

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

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

所有你可以使用 for .. in ..語法的叫做一個迭代器:鏈表,字符串,文件……你經常使用它們是因為你可以如你所愿的讀取其中的元素,但是你把所有的值都存儲到了內存中,如果你有大量數據的話這個方式并不是你想要的。

生成器(generator)

生成器是可以迭代的,但是你只可以讀取它一次 ,因為它并不把所有的值放在內存中,它是實時地生成數據:

>>> mygenerator = (x*x for x in range(3))
>>> for i in mygenerator :
...    print(i)
0
1
4

看起來除了把 [] 換成 () 外沒什么不同。但是,你不可以再次使用 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)
0
1
4

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

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

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

現在到了關鍵點了!

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

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

回到你的代碼

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

生成器:

# Here you create the method of the node object that will return the generator
def 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 reference
result, 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__() 方法)的過程。可迭代對象是你可以從其獲取到一個迭代器的任一對象。迭代器是那些允許你迭代可迭代對象的對象。

via: http://pyzh.readthedocs.org/en/latest/the-python-yield-keyword-explained.html

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,461評論 6 532
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,538評論 3 417
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,423評論 0 375
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,991評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,761評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,207評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,268評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,419評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,959評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,782評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,983評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,528評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,222評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,653評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,901評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,678評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,978評論 2 374

推薦閱讀更多精彩內容