python yield的终极解释

(译)Python关键字yield的解释(stackoverflow):

http://stackoverflow.com/questions/231767/the-python-yield-keyword-explainedhtml

 

3.1. 提问者的问题

Python关键字yield的做用是什么?用来干什么的?node

好比,我正在试图理解下面的代码:python

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

下面的是调用:ide

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 的时候发生了什么?返回了一个列表?返回了一个元素?被重复调用了么? 何时这个调用结束呢?函数

3.2. 回答部分

为了理解什么是 yield,你必须理解什么是生成器。在理解生成器以前,让咱们先走近迭代。oop

3.3. 可迭代对象

当你创建了一个列表,你能够逐项地读取这个列表,这叫作一个可迭代对象:post

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

mylist 是一个可迭代的对象。当你使用一个列表生成式来创建一个列表的时候,就创建了一个可迭代的对象:ui

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

全部你可使用 for .. in .. 语法的叫作一个迭代器:列表,字符串,文件……你常用它们是由于你能够如你所愿的读取其中的元素,可是你把全部的值都存储到了内存中,若是你有大量数据的话这个方式并非你想要的。spa

3.4. 生成器

生成器是能够迭代的,可是你 只能够读取它一次 ,由于它并不把全部的值放在内存中,它是实时地生成数据:code

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

看起来除了把 [] 换成 () 外没什么不一样。可是,你不能够再次使用 for inmygenerator , 由于生成器只能被迭代一次:先计算出0,而后继续计算1,而后计算4,一个跟一个的…

3.5. 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 条件。

3.6. 回到你的代码

(译者注:这是回答者对问题的具体解释)

生成器:

# 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只但愿它是个能够迭代的,因此这个参数能够是列表,元组,字符串,生成器... 这叫作 ducktyping,这也是为什么Python如此棒的缘由之一,但这已是另一个问题了...

你能够在这里停下,来看看生成器的一些高级用法:

3.7. 控制生成器的穷尽

>>> 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 ... 

对于控制一些资源的访问来讲这颇有用。

3.8. 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)] 

3.9. 了解迭代器的内部机理

迭代是一个实现可迭代对象(实现的是 __iter__() 方法)和迭代器(实现的是 __next__()方法)的过程。可迭代对象是你能够从其获取到一个迭代器的任一对象。迭代器是那些容许你迭代可迭代对象的对象。

更多见这个文章 http://effbot.org/zone/python-for-statement.htm

 

 

for 等迭代器的特性:

将全部数据一次性的返回给调用者,第二次调用仍是一次性的返回相同的数据(不多有不一样的状况,若是初始参数同样,基本就是每次调用返回的数据都相同)

yield 等生成器的特性:

一、它只是返回一个迭代协议(迭代原则,迭代规则,迭代方法,随你怎么想)

二、当你一次调用yield的next(),它只返回一个值,就是当前yield(的值)

三、下次调用yield的next()会从步骤2继续执行,直到遇到下一个yield,而后返回该yield(的值)

四、若是期间步骤二、3任什么时候候返回的不是yield,则整个yield结束(yield被丢弃了),之后无论你怎么调用next(准确的说,next不存在了,由于yield都没了)

示例:

def f123():
    yield 1
    yield 2
    yield 3

for item in f123():
    print item
相关文章
相关标签/搜索