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有什么用,首先得理解generators,而理解generators前還要理解iterables
Iterables
當你創建了一個列表,你可以一個一個的讀取它的每一項,這叫做iteration:
>>> mylist = [1, 2, 3]>>> for i in mylist:... PRint(i)123Mylist是可迭代的.當你用列表推導式的時候,你就創建了一個列表,而這個列表也是可迭代的:
>>> mylist = [x*x for x in range(3)]>>> for i in mylist:... print(i)014所有你可以用在for…in…語句中的都是可迭代的:比如lists,strings,files…因為這些可迭代的對象你可以隨意的讀取所以非常方便易用,但是你必須把它們的值放到內存里,當它們有很多值時就會消耗太多的內存.
Generators
生成器也是迭代器的一種,但是你只能迭代它們一次.原因很簡單,因為它們不是全部存在內存里,它們只在要調用的時候在內存里生成:
>>> mygenerator = (x*x for x in range(3))>>> for i in mygenerator:... print(i)014生成器和迭代器的區別就是用()代替[],還有你不能用for i in mygenerator第二次調用生成器:首先計算0,然后會在內存里丟掉0去計算1,直到計算完4.
Yield
Yield的用法和關鍵字return差不多,下面的函數將會返回一個生成器:
>>> def createGenerator():... mylist = range(3)... for i in mylist:... yield i*i...>>> mygenerator = createGenerator() # 創建生成器>>> print(mygenerator) # mygenerator is an object!<generator object createGenerator at 0xb7555c34>>>> for i in mygenerator:... print(i)014在這里這個例子好像沒什么用,不過當你的函數要返回一個非常大的集合并且你希望只讀一次的話,那么它就非常的方便了.
要理解Yield你必須先理解當你調用函數的時候,函數里的代碼并沒有運行.函數僅僅返回生成器對象,這就是它最微妙的地方:-)
然后呢,每當for語句迭代生成器的時候你的代碼才會運轉.
現在,到了最難的部分:
當for語句第一次調用函數里返回的生成器對象,函數里的代碼就開始運作,直到碰到yield,然后會返回本次循環的第一個返回值.所以下一次調用也將運行一次循環然后返回下一個值,直到沒有值可以返回.
一旦函數運行并沒有碰到yeild語句就認為生成器已經為空了.原因有可能是循環結束或者沒有滿足if/else之類的.
對于你的代碼的解釋
生成器:
# 這里你創建node方法的對象將會返回一個生成器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]# 在candidates上進行循環(在開始只保含一個元素)while candidates: # 獲得最后一個condidate然后從列表里刪除 node = candidates.pop() # 獲取obj和candidate的distance distance = node._get_dist(obj) # 如果distance何時將會填入result 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這段代碼有幾個有意思的地方:
一般的時候我們會在循環迭代一個列表的同時在列表中添加元素:-)盡管在有限循環里結束多少有一些危險,但也不失為一個簡單的方法去遍歷嵌套的數據.在這里candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))將遍歷生成器的每一個值,但是while循環中的condidates將不再保存已經遍歷過的生成器對象,也就是說添加進condidates的生成器對象只會遍歷一遍。
extend()是一個列表對象的方法,它可以把一個迭代對象添加進列表.
我們經常這么用:
>>> a = [1, 2]>>> b = [3, 4]>>> a.extend(b)>>> print(a)[1, 2, 3, 4]但是在你給的代碼里得到的是生成器,這樣做的好處:
你不需要讀這個值兩次 你能得到許多孩子節點但是你不希望他們全部存入內存. 這種方法之所以能很好的運行是因為Python不關心方法的參數是不是一個列表.它只希望接受一個迭代器,所以不管是strings,lists,tuples或者generators都可以!這種方法叫做duck typing,這也是Python看起來特別cool的原因之一.但是這又是另外一個傳說了,另一個問題~~
好了,看到這里可以打住了,下面讓我們看看生成器的高級用法:
控制迭代器的窮盡
>>> class Bank(): # 讓我們建個銀行,生產許多ATM... crisis = False... def create_atm(self):... while not self.crisis:... yield "$100">>> hsbc = Bank() # 當一切就緒了你想要多少ATM就給你多少>>> 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 # cao,經濟危機來了沒有錢了!>>> print(corner_street_atm.next())<type 'exceptions.StopIteration'>>>> wall_street_atm = hsbc.create_atm() # 對于其他ATM,它還是True>>> print(wall_street_atm.next())<type 'exceptions.StopIteration'>>>> hsbc.crisis = False # 麻煩的是,盡管危機過去了,ATM還是空的>>> print(corner_street_atm.next())<type 'exceptions.StopIteration'>>>> brand_new_atm = hsbc.create_atm() # 只能重新新建一個bank了>>> for cash in brand_new_atm:... print cash$100$100$100$100$100$100$100$100$100...它對于一些不斷變化的值很有用,像控制你資源的訪問.
Itertools,你的好基友
itertools模塊包含了一些特殊的函數可以操作可迭代對象.有沒有想過復制一個生成器?鏈接兩個生成器?把嵌套列表里的值組織成一個列表?Map/Zip還不用創建另一個列表?
來吧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()方法)的一個過程.可迭代對象就是任何你可以迭代的對象(廢話啊).迭代器就是可以讓你迭代可迭代對象的對象(有點繞口,意思就是這個意思)
新聞熱點
疑難解答