“yield”关键字有什么作用?

发布于 2022-01-03 17:00:14

yieldPython中的关键字有什么用?它有什么作用?

例如,我试图理解这个代码1

def _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 = [], [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调用方法时会发生什么?是否返回列表?单个元素?又叫了吗?后续呼叫何时停止?

关注者
0
被浏览
117
1 个回答
  • 面试哥
    面试哥 2022-01-03
    为面试而生,有面试问题,就找面试哥。

    要了解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

    生成器是迭代器,一种只能迭代一次的可迭代对象。生成器不会将所有值存储在内存中,它们会即时生成值

    >>> 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 create_generator():
    ...    mylist = range(3)
    ...    for i in mylist:
    ...        yield i*i
    ...
    >>> mygenerator = create_generator() # create a generator
    >>> print(mygenerator) # mygenerator is an object!
    <generator object create_generator 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
    

    此代码包含几个智能部分:

    • 循环对列表进行迭代,但在循环迭代时列表会扩展。这是遍历所有这些嵌套数据的简洁方法,即使它有点危险,因为您最终可能会陷入无限循环。在这种情况下,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]
    

    但是在您的代码中,它获得了一个生成器,这很好,因为:

    1. 您不需要两次读取这些值。
    2. 你可能有很多孩子,你不希望他们都存储在内存中。

    它之所以有效是因为 Python 并不关心方法的参数是否是列表。Python 需要可迭代对象,因此它可以处理字符串、列表、元组和生成器!这称为鸭子类型,这也是 Python 如此酷的原因之一。但这是另一个故事,对于另一个问题......

    你可以停在这里,或者读一点来看看生成器的高级用法:

    Controlling a generator exhaustion

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

    注意:对于 Python 3,使用print(corner_street_atm.__next__())print(next(corner_street_atm))

    它可用于控制对资源的访问等各种事情。

    Itertools,你最好的朋友

    itertools 模块包含操作可迭代对象的特殊函数。曾经想复制一个生成器吗?连接两个发电机?使用单行对嵌套列表中的值进行分组?Map / Zip不创建另一个列表?

    那么就import itertools.

    一个例子?让我们看看四马比赛可能的到达顺序:

    >>> 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__()方法)的过程。可迭代对象是您可以从中获取迭代器的任何对象。迭代器是让你迭代可迭代对象的对象。

    这篇文章中有更多关于循环如何for工作的内容



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看