Python 中产出关键字的用法是什么? 它能做什么?

例如,我试图理解这个代码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_camedates 被调用时会怎样? 列表是否返回? 单一个元素吗? 是否再次调用? 以后的电话何时停止?


1. 本代码由Jochen Schulz(jrschulz)编写,他为公制空间制作了一个伟大的Python图书馆,与完整的源:模块mspace链接。


当前回答

就像有人要你做5个纸杯蛋糕一样。如果你做了至少一个纸杯蛋糕,你可以在做其他蛋糕时给他们吃。

In [4]: def make_cake(numbers):
   ...:     for i in range(numbers):
   ...:         yield 'Cake {}'.format(i)
   ...:

In [5]: factory = make_cake(5)

这里称为发电机, 它会做蛋糕。 如果您叫作 Make_ 函数, 您可以得到一个发电机, 而不是运行此函数。 这是因为当输出关键字出现在一个函数中时, 它会变成一个生成器 。

In [7]: next(factory)
Out[7]: 'Cake 0'

In [8]: next(factory)
Out[8]: 'Cake 1'

In [9]: next(factory)
Out[9]: 'Cake 2'

In [10]: next(factory)
Out[10]: 'Cake 3'

In [11]: next(factory)
Out[11]: 'Cake 4'

他们消耗了所有的蛋糕, 但他们又要求一个。

In [12]: next(factory)
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-12-0f5c45da9774> in <module>
----> 1 next(factory)

StopIteration:

并且他们被告知不要问更多的问题。 所以一旦你消耗了发电机, 你就会用它做。 如果你想要更多的蛋糕,你需要再打电话做蛋糕。 这就像再订一份蛋糕。

In [13]: factory = make_cake(3)

In [14]: for cake in factory:
    ...:     print(cake)
    ...:
Cake 0
Cake 1
Cake 2

您也可以使用上面的生成器来循环。

举个例子:假设你每次问密码时都想要随机密码。

In [22]: import random

In [23]: import string

In [24]: def random_password_generator():
    ...:     while True:
    ...:         yield ''.join([random.choice(string.ascii_letters) for _ in range(8)])
    ...:

In [25]: rpg = random_password_generator()

In [26]: for i in range(3):
    ...:     print(next(rpg))
    ...:
FXpUBhhH
DdUDHoHn
dvtebEqG

In [27]: next(rpg)
Out[27]: 'mJbYRMNo'

这里的 rpg 是一个生成器, 它可以生成无限数量的随机密码。 所以我们也可以说, 当我们不知道序列的长度时, 生成器是有用的, 不同于列表, 列表中有一定数量的元素 。

其他回答

这样想吧:

迭代器只是具有下一个( ) 方法的对象的奇特探测术语。 因此, 产生式的函数最终会变成这样 :

原文:

def some_function():
    for i in xrange(4):
        yield i

for i in some_function():
    print i

Python 翻译用上述代码所做的基本上就是:

class it:
    def __init__(self):
        # Start at -1 so that we get 0 when we add 1 below.
        self.count = -1

    # The __iter__ method will be called once by the 'for' loop.
    # The rest of the magic happens on the object returned by this method.
    # In this case it is the object itself.
    def __iter__(self):
        return self

    # The next method will be called repeatedly by the 'for' loop
    # until it raises StopIteration.
    def next(self):
        self.count += 1
        if self.count < 4:
            return self.count
        else:
            # A StopIteration exception is raised
            # to signal that the iterator is done.
            # This is caught implicitly by the 'for' loop.
            raise StopIteration

def some_func():
    return it()

for i in some_func():
    print i

为了更深入地了解幕后发生的事情,

iterator = some_func()
try:
    while 1:
        print iterator.next()
except StopIteration:
    pass

这更有意义还是更让人困惑?

我要指出,为了说明起见,这过于简单化。 )

一个容易理解它是什么的简单例子:产量

def f123():
    for _ in range(4):
        yield 1
        yield 2


for i in f123():
    print (i)

产出是:

1 2 1 2 1 2 1 2

所有的答案都是伟大的, 但对于新人来说有点困难。

我猜你已经得知回程声明了

作为类比,回归和收益是双胞胎。 回归意味着“ 回归和停止 ” , 而“ 回归”则意味着“回归,但继续 ” 。

尝试获得一份有回报的 num_ 列表 。

def num_list(n):
    for i in range(n):
        return i

运行它:

In [5]: num_list(3)
Out[5]: 0

你看,你只得到一个数字,而不是一个他们的名单。返回永远不允许你快乐地获胜,只要执行一次就退出。

产生结果

将返回替换为产出 :

In [10]: def num_list(n):
    ...:     for i in range(n):
    ...:         yield i
    ...:

In [11]: num_list(3)
Out[11]: <generator object num_list at 0x10327c990>

In [12]: list(num_list(3))
Out[12]: [0, 1, 2]

现在,你赢得了所有的数字。

与一次运行和停止的返回相比, 一次运行和一次运行, 一次运行和一次运行。 您可以将返回解释为一个返回, 一次返回作为全部返回。 这叫“ 易动 ” 。

再多走一步,我们就可以重新写出回报的收益声明

In [15]: def num_list(n):
    ...:     result = []
    ...:     for i in range(n):
    ...:         result.append(i)
    ...:     return result

In [16]: num_list(3)
Out[16]: [0, 1, 2]

这是关于产量的核心。

列表返回输出与目标产出的区别是:

您总是可以从列表对象中获取 [0, 1, 2] , 但只能从“ 对象输出输出” 中提取一次 。 因此, 它有一个新的名称生成对象, 如 Out[ 11] 所示 : <generator 对象 num_ list at 0x10327c990> 。

最后,作为格罗克语的比喻:

双胞胎名单和发电机是双胞胎

产出关键字简化为两个简单的事实:

如果编译者在函数内的任何地方检测到产出关键字,则该关键字函数不再通过返回语句返回。相反,它会立即返回一个称为生成器的懒惰的“待决列表”对象。“生成器”是可循环的。什么是可循环的?它像列表或设置或范围或编辑视图一样,带有按一定顺序访问每个元素的内置协议。

简言之: 最常见的情况是, 发电机是一个懒惰的、 递增的等待列表, 并且产出语句允许您使用函数符号来编程生成器应该逐渐吐出的列表值。 此外, 高级用法允许您使用发电机作为共程( 见下文 ) 。

generator = myYieldingFunction(...)  # basically a list (but lazy)
x = list(generator)  # evaluate every element into a list

   generator
       v
[x[0], ..., ???]

         generator
             v
[x[0], x[1], ..., ???]

               generator
                   v
[x[0], x[1], x[2], ..., ???]

                       StopIteration exception
[x[0], x[1], x[2]]     done

基本上, 只要遇到产出语句, 函数就会暂停并保存状态, 然后根据 Python 传动协议( 在某些合成结构中, 类似反复呼叫下一个( ) 的循环, 并捕捉一个停止作用的例外等) , 发出“ 列表中的下一个返回值 ” 。 您可能遇到过带有生成表达式的生成器; 生成函数更强大, 因为您可以将参数反馈到暂停的生成器功能中, 使用它们来实施 comutines 。 稍后会更多 。


基本示例(“清单”)

我们来定义一个函数,它就像 Python 的射程。 调用 makeRange(n) returns a Generator:

def makeRange(n):
    # return 0,1,2,...,n-1
    i = 0
    while i < n:
        yield i
        i += 1

>>> makeRange(5)
<generator object makeRange at 0x19e4aa0>

要强制生成器立即返回其未完成的值, 您可以将它传送到列表 () (就像您可以任意使用 ) :

>>> list(makeRange(5))
[0, 1, 2, 3, 4]

比较“仅返回列表”的示例

上述例子可视为仅仅是创建一份清单,并附在后面并返回:

# return a list                  #  # return a generator
def makeRange(n):                #  def makeRange(n):
    """return [0,1,2,...,n-1]""" #      """return 0,1,2,...,n-1"""
    TO_RETURN = []               # 
    i = 0                        #      i = 0
    while i < n:                 #      while i < n:
        TO_RETURN += [i]         #          yield i
        i += 1                   #          i += 1
    return TO_RETURN             # 

>>> makeRange(5)
[0, 1, 2, 3, 4]

不过,有一个重大差别;见最后一节。


您如何使用发电机

所有发电机都是易变的, 所以它们经常被这样使用:

#                  < ITERABLE >
>>> [x+10 for x in makeRange(5)]
[10, 11, 12, 13, 14]

要对发电机有更好的感觉,您可以玩过工具模块( 一定要使用链。 来自_ irightable, 而不是当必要时使用链子 ) 。 例如, 您甚至可以使用生成器来实施无限长的懒惰列表, 比如 ltertools. counts () 。 您可以执行您自己的除法列表( 可认证的) : zip( 计数 ) , 或使用一段时间内生成关键字来这样做 。

请注意: 发电机实际上可以用于更多的事情, 比如实施 comotines 或非 确定性编程或其他优雅的东西。 然而, 我在此介绍的“ 懒惰列表” 观点是您最常用的 。


幕后幕后

这就是“ Python 迭代协议” 的原理。 也就是说, 当您做列表( makeRange(5)) 时会发生什么 。 这就是我前面描述的“ 懒惰、 递增列表 ” 。

>>> x=iter(range(5))
>>> next(x)  # calls x.__next__(); x.next() is deprecated
0
>>> next(x)
1
>>> next(x)
2
>>> next(x)
3
>>> next(x)
4
>>> next(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

内建函数的下一个 () 只是调用对象 ._next__ () 函数, 这是“ 电路协议” 的一部分, 并在所有迭代器中找到 。 您可以手动使用下一个( ) 函数( 和迭代协议的其他部分) 来执行奇特的东西, 通常以降低可读性为代价, 所以尽量避免这样做...


锥体

圆柱形示例:

def interactiveProcedure():
    userResponse = yield makeQuestionWebpage()
    print('user response:', userResponse)
    yield 'success'

coroutine = interactiveProcedure()
webFormData = next(coroutine)  # same as .send(None)
userResponse = serveWebForm(webFormData)

# ...at some point later on web form submit...

successStatus = coroutine.send(userResponse)

comotine (generations 通常接受通过 产出 关键字输入输入 , 例如, 下一个 Input = 产生下一个输出, 作为一种双向通信形式) 基本上是允许暂停自己和请求输入的计算( 例如它下一步应该做什么 ) 。 当 comotine 暂停自己( 当运行中的 comotine 最终会点击 产出 关键字时) , 计算会暂停, 控制会被倒回“ 调” 函数( 要求下一个计算值的框架 ) 。 暂停的发电机/ 库外 仍然暂停, 直到另一个函数( 可能是一个不同的函数/ 文本) 启用后, 请求下一个值( 通常通过输入数据将暂停的逻辑内部输入到 comutine 的代码 ) 。

您可以将皮延共程视为懒惰的递增待决列表, 下一个元素不仅取决于先前的计算, 而且还取决于输入, 您可以选择在生成过程中注射 。


贫提亚e

通常,大多数人不会关心以下的区别,可能想在这里停止阅读。

在 Python-speak 中, 迭代是“ 理解“ 循环概念” 的任何物体, 如列表[ 1, 2, 3] , 转动器是请求循环的具体实例, 如 [ 1, 2, 3,. . _ eter __ () 。 生成器与任何迭代器完全相同, 但它的写法除外( 带有函数语法 ) 。

当您从列表中请求一个迭代器时, 它会创建一个新的迭代器。 但是, 当您从一个迭代器中请求一个迭代器( 您很少会这样做 ) 时, 它只会给您一个副本 。

因此,在不可能的情况下,你没有 做这样的事情...

> x = myRange(5)
> list(x)
[0, 1, 2, 3, 4]
> list(x)
[]

... 然后记住发电机是一个迭代器, 也就是说, 它是一次性使用。 如果您想要再使用它, 您应该再次调用 MyRange (...) 。 如果您需要使用结果两次, 将结果转换为列表, 并存储在变量 x = 列表( MyRange (5)) 中。 那些绝对需要克隆生成器的人( 例如, 那些正在做可怕的黑客化元程序设计的人) 可以使用它的工具.tee( 仍然在 Python 3 中工作) , 如果绝对需要的话, 因为可复制的迭代器 Python PEP 标准建议已被推迟 。

生成关键字用于查点/字符,其中函数预期将返回一个输出。我想引用这个非常简单的例A:

# example A
def getNumber():
    for r in range(1,10):
        return r

以上函数只返回一次, 即使它被多次调用。 现在如果我们以收益率替换返回, 如例B :

# example B
def getNumber():
    for r in range(1,10):
        yield r

当第一次叫2时,它会返回1,当再次叫2时,3,4,然后它会递增到10。

虽然B的例子在概念上是真实的,但要用Python 3来称呼它,我们必须采取以下行动:


g = getNumber() #instance
print(next(g)) #will print 1
print(next(g)) #will print 2
print(next(g)) #will print 3

# so to assign it to a variables
v = getNumber()
v1 = next(v) #v1 will have 1
v2 = next(v) #v2 will have 2
v3 = next(v) #v3 will have 3