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
   / \
  3   6
 / \   \
1   4   8

另一个简单的二进制搜索树的十字路口:

class Node(object):
..
def __iter__(self):
    if self.has_left_child():
        for child in self.left:
            yield child

    yield self.val

    if self.has_right_child():
        for child in self.right:
            yield child

执行代码在树形对象上,它执行__iter___这样:

def __iter__(self):

    class EmptyIter():
        def next(self):
            raise StopIteration

    if self.root:
        return self.root.__iter__()
    return EmptyIter()

候选人发言可用树上元素替换; Python 翻译为

it = iter(TreeObj)  # returns iter(self.root) which calls self.root.__iter__()
for element in it: 
    .. process element .. 

因为节点. _ iter_ 函数是一个生成器, 内部的代码按迭代执行 。 所以执行会是这样的 :

根元素是第一个; 检查它是否留下了孩子, 并且要循环它们( 因为我们叫它它 1 ) 。 它有一个孩子, 所以执行它。 给孩子自己。 左左为自己创建一个新的循环器 。 左是节点对象本身( it2) 。 左是同一逻辑 2 , 新的循环器已经创建( it3) 。 现在我们到达了树的左端 。 现在我们到达了树的左端。 它3 没有留下孩子, 所以它会继续下去并产生自我。 在下一个呼叫( it3) 时, 它会提高停止作用, 因为它没有正确的孩子( 到达函数的尽头, 但没有产生任何效果) 。 它1 和它2 仍然在活动 - 它们没有耗尽, 调用下一个( it2) 将产生值, 而不是提高停止作用 。 现在我们回到了它的上下文 2 , 并调下一个( it2) 继续它停止它的地方 : 在产生子声明之后 。 由于它没有更多的剩余孩子, 它会继续持续并产生自我 val 。 val 。

这里的渔获是,每次迭代都会产生次标准来绕过树,并保持当前迭代的状态。 一旦它到达终点,它就会绕过堆叠,并按正确的顺序返回值( 最小的收益值首先 ) 。

您的代码示例在一种不同的技术中做了类似的事情: 它为每个孩子输入了一个元素列表, 然后在下一个迭代中, 它弹出它, 并在当前对象上运行函数代码( 也就是自定义 ) 。

我希望这对这个传奇话题有一点帮助,我花了好几个小时来画这个过程来理解它。

其他回答

我本打算张贴“Beazley的“Python:基本参考”第19页,

另外,请注意, 产量可以作为发电机功能中的双重用途, 共程中可以使用。 虽然这与您的代码片断不相同, 但( ield) 也可以用作函数中的表达方式。 当调用者使用发送( ) 方法给方法发送一个值时, 共程将执行到遇到下一个( yeld) 语句时 。

生成器和共同路由是建立数据流类型应用程序的很酷的方法。 我认为值得知道在函数中产出语句的另一种用途。

要了解什么是产量,你必须了解什么是发电机。在你能够理解发电机之前,你必须了解易燃的发电机。

易变性

创建列表时,您可以逐项阅读其项目。逐项阅读其项目被称为迭代:

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

My list 是可替换的。 当您使用列表理解时, 您会创建一个列表, 因而是一个可替换的 :

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

你可以使用的一切"... 在..."是一个可循环的; 列表,字符串,文件...

这些可替换的功能是实用的,因为您可以随心所欲地阅读,但您将所有值都存储在记忆中,当您拥有很多值时,这并不总是你想要的。

发电机发电机

发电机是迭代器, 一种可迭代的循环, 您只能循环一次 。 发电机不会存储记忆中的所有值, 它们会在苍蝇上生成值 :

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

除了使用()而不是使用()之外,它是一样的。但是,由于发电机只能使用一次,所以不能在我的生成器中为我第二次执行,因为发电机只能使用一次:它们计算0,然后忘记它,然后计算1,然后结束计算4,一个一个一个地计算。

产量d

函数将返回一个生成器。

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

这是一个毫无用处的例子, 但当你知道你的功能会返回 一大堆的值时, 它就方便了, 你只需要读一次。

要掌握输出能力, 您必须明白当您调用函数时, 您在函数体中写入的代码没有运行。 函数只返回生成对象, 这有点棘手 。

然后,你的代码会继续 从它离开的每一次 使用发电机。

现在,硬的部分:

第一次调用您函数所创建的生成器对象时, 它会运行您函数的代码, 从开始到它产生, 然后返回循环的第一个值。 然后, 以后每次调用都会运行您在函数中写入的循环的再次迭代, 然后返回下一个值。 这将一直持续到生成器被认为是空的, 当函数运行时不会打出收益。 这可能是因为循环结束, 或者因为您不再满足“ if/ else ” 。


您的代码解释

发电机:

# 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 are 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 the distance is ok, then you can fill in the result
    if distance <= max_dist and distance >= min_dist:
        result.extend(node._values)

    # Add the children of the candidate to the candidate's list
    # so the loop will keep running until it has 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

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

在列表中循环迭代, 但列表会随着循环迭代而扩展。 这是一个简单的方式来查看所有这些嵌套的数据, 即使它是一个有点危险的, 因为您可以以无限环结束。 在此情况下, 候选人 。 extendend( rode._ get_ child_ camedates( root, min_ dist, max_ distist)) 将耗尽所有生成器的值, 但同时继续创建新生成的生成对象, 这些对象将产生与先前的相异的值, 因为它不会被应用到同一个节点上 。 扩展 () 方法是一种列表对象方法, 期待一个可重复的列表对象方法, 并将其添加到列表中 。

通常,我们向它传递一份清单:

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

但在你的代码中,它有一个发电机, 这是很好的,因为:

你不需要两次阅读这些值。 你可能有很多孩子, 你不想把他们都保存在记忆中。

之所以有效,是因为 Python 并不在意一种方法的论据是否是一个列表。 Python 期望它能用字符串、列表、图普勒和生成器来操作。 这叫做鸭字打字, 也是Python之所以如此酷的原因之一。 但是这是另一个故事, 另一个问题...

您可以在这里停下来,或者读一下,看一个生成器的先进使用:

控制发电机耗竭

>>> 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, 使用打印( corner_street_atm._next___ ()) 或打印( ext( corner_ street_ atm) )

它可以对控制获取资源等各种事情有用。

义大便,你最好的朋友

Itertool 模块包含操作可替换文件的特殊功能 。 是否想要复制一个生成器? 连锁二生成器? 组值在单行的嵌套列表中? 地图/ Zip 不创建另一个列表 ?

然后就进口它的工具。

举个例子,让我们看看四匹马赛的到货订单

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

了解迭代的内部机制

迭代是一个过程, 意味着可迭代( 实施 _ etre_ () 方法) 和迭代( 实施 ext_ () 方法) 。 迭代是您可以从中获取迭代器的任何对象。 迭代器是允许您循环到可迭代的物体 。

本文中有更多关于环环如何运作的论述。

- 功能 - 返回。

发电机 -- -- 产量(含有一个或多个产量和零或更多回报率)。

names = ['Sam', 'Sarah', 'Thomas', 'James']


# Using function
def greet(name) :
    return f'Hi, my name is {name}.'
    
for each_name in names:
    print(greet(each_name))

# Output:   
>>>Hi, my name is Sam.
>>>Hi, my name is Sarah.
>>>Hi, my name is Thomas.
>>>Hi, my name is James.


# using generator
def greetings(names) :
    for each_name in names:
        yield f'Hi, my name is {each_name}.'
 
for greet_name in greetings(names):
    print (greet_name)

# Output:    
>>>Hi, my name is Sam.
>>>Hi, my name is Sarah.
>>>Hi, my name is Thomas.
>>>Hi, my name is James.

发电机看起来像一个函数,但行为举止却像一个迭代器。

发件人继续从它所在的位置执行 。 恢复后, 函数在最后产值运行后立即继续执行 。 这允许它的代码在一段时间内生成一系列的值, 代之以它们一次性计算全部值, 然后把它们像列表一样送回去 。

def function():
    yield 1 # return this first
    yield 2 # start continue from here (yield don't execute above code once executed)
    yield 3 # give this at last (yield don't execute above code once executed)

for processed_data in function(): 
    print(processed_data)
    
#Output:

>>>1
>>>2
>>>3

注:放弃不应在尝试中.最终建造。

输出是函数的返回元素。 区别在于, 产出元素将函数转换成生成器。 生成器的行为就像一个函数, 直到某种“ 归属 ” 。 生成器停止直到下一次调用, 并且从与开始的完全相同的点继续。 您可以通过调用列表( 生成器 () ) 获得一个序列中所有“ 属性” 值的序列。

总之,产出语句将您的函数转换成一个工厂,该工厂生产一个特殊对象,称为发电机,围绕您原始函数的正文包绕。当生成器被迭代时,它将执行您的函数,直到达到下一个输出时,然后中止执行,然后对传递到的数值进行评估。它重复了每次迭代的这一过程,直到执行路径退出函数。例如,

def simple_generator():
    yield 'one'
    yield 'two'
    yield 'three'

for i in simple_generator():
    print i

简单产出

one
two
three

电源来自使用循环计算序列的生成器, 生成器执行循环每次停止到“ ield ” 的下一个计算结果, 这样它就可以计算飞行上的列表, 好处是存储到特别大的计算中的内存

说你想创建一个自己的范围函数, 产生一个可循环的数字范围, 你可以这样做,

def myRangeNaive(i):
    n = 0
    range = []
    while n < i:
        range.append(n)
        n = n + 1
    return range

并像这样使用它;

for i in myRangeNaive(10):
    print i

但这效率低,因为

您创建了一个只使用一次的数组( 此废物内存) 。 此代码实际上会两次循环到该数组上 ! : () : ()

幸好吉多和他的团队 慷慨地开发了发电机 这样我们就可以这么做了

def myRangeSmart(i):
    n = 0
    while n < i:
       yield n
       n = n + 1
    return

for i in myRangeSmart(10):
    print i

在每次迭代中, 调用下一个发电机的函数执行该函数, 直至它到达“ ield” 语句停止和“ ields” 值, 或到达函数的终点。 在第一次调用的情况下, 下一个( ) 执行到产出语句, 并产生“ n ” , 下次调用它将执行递增语句, 跳回“ 此时” , 评估它, 如果是, 它会停止并再次产生“ n ” , 它会一直持续到状态返回错误, 发电机跳到函数结束的时候 。