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链接。


当前回答

对于那些更喜欢最低限度工作实例的人来说,考虑一下这次交互式的Python会议:

>>> def f():
...   yield 1
...   yield 2
...   yield 3
... 
>>> g = f()
>>> for i in g:
...   print(i)
... 
1
2
3
>>> for i in g:
...   print(i)
... 
>>> # Note that this time nothing was printed

其他回答

产出 :

可以通过停止函数从函数返回一个值的多次。 您可以从它中返回一个值, 如从中产生 。 当返回大数据时, 将它分成小部分数据, 以防止大量使用内存 。

例如,下面的测试 () 可以通过停止测试( ) 逐个返回“ 1 ” 、 “ 2 ” 和 [ “ 3 ” 、 “ 四 ” 。 因此, 测试( ) 总共返回3倍, 总共返回3倍, 停止测试( ) 共返回3倍 :

def test():
    yield 'One'                  # Stop, return 'One' and resume 
    yield 'Two'                  # Stop, return 'Two' and resume
    yield from ['Three', 'Four'] # Stop and return ['Three', 'Four'] 

下面这三套代码可以调用测试() 并打印“ 1 ” 、 “ 2 ” 、 “ 三 ” 和 “ 四 ” :

for x in test():
    print(x)
x = test()
print(next(x))
print(next(x))
print(next(x))
print(next(x))
x = test()
print(x.__next__())
print(x.__next__())
print(x.__next__())
print(x.__next__())

其结果是:

$ python yield_test.py
One
Two
Three
Four

此外,在利用回报和产出时,没有办法从回报中获得价值:

def test():
    yield 'One' 
    yield 'Two'
    yield from ['Three', 'Four']
    return 'Five' # 'Five' cannot be got

x = test()
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x)) # Here

因此,在试图获取“ 五” 时, 下面有一个错误 :

$ python yield_test.py 
One
Two
Three
Four
Traceback (most recent call last):
  File "C:\Users\kai\yield_test.py", line 12, in <module>
    print(next(x))
          ^^^^^^^
StopIteration: Five

以下是一个简单的例子:

def isPrimeNumber(n):
    print "isPrimeNumber({}) call".format(n)
    if n==1:
        return False
    for x in range(2,n):
        if n % x == 0:
            return False
    return True

def primes (n=1):
    while(True):
        print "loop step ---------------- {}".format(n)
        if isPrimeNumber(n): yield n
        n += 1

for n in primes():
    if n> 10:break
    print "wiriting result {}".format(n)

产出:

loop step ---------------- 1
isPrimeNumber(1) call
loop step ---------------- 2
isPrimeNumber(2) call
loop step ---------------- 3
isPrimeNumber(3) call
wiriting result 3
loop step ---------------- 4
isPrimeNumber(4) call
loop step ---------------- 5
isPrimeNumber(5) call
wiriting result 5
loop step ---------------- 6
isPrimeNumber(6) call
loop step ---------------- 7
isPrimeNumber(7) call
wiriting result 7
loop step ---------------- 8
isPrimeNumber(8) call
loop step ---------------- 9
isPrimeNumber(9) call
loop step ---------------- 10
isPrimeNumber(10) call
loop step ---------------- 11
isPrimeNumber(11) call

我不是Python开发者,但对我来说,它似乎保持了程序流程的位置,而下一个循环则从“当量”的位置开始。 它似乎正在等待着这个位置,就在那个位置之前,它正在向外回报一个价值,而下一次将继续工作。

这似乎是一个有趣和好的能力:

下面是浅白语言的例子。我将提供高层次人类概念与低层次Python概念之间的对应关系。

我想用数字序列操作, 但我不想用这个序列的创建来烦恼我自己, 我只想专注于我想做的操作。 因此, 我做以下工作:

我打电话给你并告诉你,我想要一个以特定方式计算的数字序列,我告诉你算法是什么。 这个步骤对应着定义发电机的函数, 也就是包含一个产出的函数。 稍后我告诉你, “ 好, 准备好告诉我数字的序列 ” 。 这个步骤对应着调用发电机的函数, 返回一个发电机对象。 注意不要告诉我任何数字; 你只是拿起你的纸张和铅笔。 我问你, “ 请告诉我下一个数字 ” , 然后你告诉我第一个数字; 之后, 你等着我问你下一个数字。 这是你的任务, 也就是确定你所在的位置, 你已经说过的数字, 下一个数字是什么。 我不在乎细节。 这个步骤相当于在发电机对象上调用下一个( 发电机) 号码的方法。 ( Python 2, next) 注意, 这是一个发电机对象的方法; 在 Python 3, 它被命名为...

这是生成器所做的( 包含一个产值的函数 ) ; 它开始在第一个( ) 上执行, 当它做一个产值时暂停, 当要求下一个( ) 值时, 它会从最后一点继续 。 它的设计完全符合 Python 的循环协议, 协议描述如何按顺序要求值 。

迭代协议最著名的用户是 Python 的命令用户。 所以, 当你做 :

for item in sequence:

序列是否是一个列表、字符串、字典或上述生成对象并不重要;结果是一样的:您逐个阅读序列中的项目。

请注意,定义含有产出关键字的函数不是创建生成器的唯一方法;它只是创建生成器的最简单的方法。

欲知更准确的信息,请阅读Python文件中的迭代机类型、产量说明和发电机。

生成关键字用于查点/字符,其中函数预期将返回一个输出。我想引用这个非常简单的例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

产量的另一种用途和含义(自Python3.3以来):

yield from <expr>

PEP380 -- -- 属于子发电机的语法:

提议对发电机使用语法将部分操作权下放给另一个发电机。 这样可以将含有“ ield” 的代码部分输入到另一个发电机中。 此外, 允许次发电机返回一个值, 并将价值提供给授权发电机。 新的语法也为当一台发电机再生价值时实现优化开辟了某些机会 。

此外,这将引入(自Python3.5以来):

async def new_coroutine(data):
   ...
   await blocking_action()

以避免与正常发电机混为一谈(两者均使用每天的产量)。