stackoverflow yield

原文地址:https://stackoverflow.com/questions/231767/what-does-the-yield-keyword-do
为了理解什么是yield,你必须理解什么是生成器。在你理解什么是生成器之前,你必须理解可迭代对象

Iterables(可迭代对象)

当你创建一个列表时,你可以一个接一个地读取他的内容。一个接一个读取它的内容叫做迭代:

>>> 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 ...的都是一个可迭代对象。lists,strings.文件。

这些可迭代对象都是容易使用的,因为你想读多少就读多少数据,但是你把这些存在内存中,你不总是都需要当你有一大堆值的时候。

Generators(生成器)

生成器都是可迭代对象,是一种你只能迭代一次的可迭代对象、生成器不存储在内存中的所有值,他们动态地(on the fly)生成值。

>>> 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调用这个生成器那里继续运行。(这里的翻译存在一些问题)

现在是复杂的部分:
for第一次调用从你的函数中创建的生成器对象,它会运行你函数里的代码知道它遇到yield,然后它会返回这个循环的第一个值。然后,接下来的每一次调用都会运行另一个你卸载函数里的循环的迭代,返回下一个值。这会继续知道生成器被认为是空的,发生在当函数运行到遇不上yield。这是因为循环已经走到终点,或者没有再匹配if/else

对于问题代码的解释

Generator:

# Here you create the method of the node object that will return the generator
def _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 the 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 the 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

Caller:

# 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 candidate's 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

这个代码包含了这几个聪明的部分:

  • 循环在一个列表上迭代,但是列表在循环被迭代时拓展。这是一个简洁的方式,用来遍历那些嵌套数据,尽管它有一些危险,因为你可能陷入死循环。
  • extend()方法是一个列表对象方法,需要一个可迭代对象,然后将它的值加入列表。

我们通常传递一个列表给它:

>>> a = [1, 2]
>>> b = [3, 4]
>>> a.extend(b)
>>> print(a)
[1, 2, 3, 4]

但是在你的代码中。它接收了一个生成器,是好的做法因为:

  1. 你不需要再次读取这些数据。
  2. 你可能有一大堆children,然后你不想把他们存储在内存中。

它是起作用的因为Python不在于这个方法的参数是否是一个列表。Python需要可迭代对象,所以strings,lists,tuples,generators都是起作用的。这叫做duck typing,这也是Python为什么cool的一个理由。但是这是另一个故事,是为了另一个问题。

你可以再这里停下,或者阅读更多的内容去看生成器的高阶用法。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值