Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
234 views
in Technique[技术] by (71.8m points)

python - “ yield”关键字有什么作用?(What does the “yield” keyword do?)

What is the use of the yield keyword in Python?

(Python中yield关键字的用途是什么?)

What does it do?

(它有什么作用?)

For example, I'm trying to understand this code 1 :

(例如,我试图理解这段代码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  

And this is the caller:

(这是呼叫者:)

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

What happens when the method _get_child_candidates is called?

(调用_get_child_candidates方法时会发生什么?)

Is a list returned?

(是否返回列表?)

A single element?

(一个元素?)

Is it called again?

(再叫一次吗?)

When will subsequent calls stop?

(后续通话何时停止?)


1. This piece of code was written by Jochen Schulz (jrschulz), who made a great Python library for metric spaces.

(1.这段代码是由Jochen Schulz(jrschulz)编写的,Jochen Schulz是一个很好的用于度量空间的Python库。)

This is the link to the complete source: Module mspace .

(这是完整源代码的链接: Module mspace)

  ask by Alex. S. translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To understand what yield does, you must understand what generators are.

(要了解什么是yield ,您必须了解什么是发电机 。)

And before you can understand generators, you must understand iterables .

(而且,在您了解生成器之前,您必须了解iterables 。)

Iterables (可迭代)

When you create a list, you can read its items one by one.

(创建列表时,可以一一阅读它的项目。)

Reading its items one by one is called iteration:

(逐一读取其项称为迭代:)

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

mylist is an iterable .

(mylist可迭代的 。)

When you use a list comprehension, you create a list, and so an iterable:

(当您使用列表推导时,您将创建一个列表,因此是可迭代的:)

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

Everything you can use " for... in... " on is an iterable;

(您可以for... in...上使用“ for... in... ”的所有内容都是可迭代的;)

lists , strings , files...

(listsstrings ,文件...)

These iterables are handy because you can read them as much as you wish, but you store all the values in memory and this is not always what you want when you have a lot of values.

(这些可迭代的方法很方便,因为您可以随意读取它们,但是您将所有值都存储在内存中,当拥有很多值时,这并不总是想要的。)

Generators (发电机)

Generators are iterators, a kind of iterable you can only iterate over once .

(生成器是迭代器,一种迭代, 您只能迭代一次 。)

Generators do not store all the values in memory, they generate the values on the fly :

(生成器不会将所有值存储在内存中, 它们会即时生成值 :)

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

It is just the same except you used () instead of [] .

(除了使用()代替[]之外,其他操作都相同。)

BUT, you cannot perform for i in mygenerator a second time since generators can only be used once: they calculate 0, then forget about it and calculate 1, and end calculating 4, one by one.

(但是,您不能第二次for i in mygenerator执行for i in mygenerator因为生成器只能使用一次:它们先计算0,然后忘记它并计算1,最后一次计算4。)

Yield (产量)

yield is a keyword that is used like return , except the function will return a generator.

(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

Here it's a useless example, but it's handy when you know your function will return a huge set of values that you will only need to read once.

(这是一个无用的示例,但是当您知道函数将返回大量的值(只需要读取一次)时,它就很方便。)

To master yield , you must understand that when you call the function, the code you have written in the function body does not run.

(要掌握yield ,您必须了解在调用函数时,在函数主体中编写的代码不会运行。)

The function only returns the generator object, this is a bit tricky :-)

(该函数仅返回生成器对象,这有点棘手:-))

Then, your code will continue from where it left off each time for uses the generator.

(然后,您的代码将继续从它每次离开的地方for使用发电机。)

Now the hard part:

(现在最困难的部分是:)

The first time the for calls the generator object created from your function, it will run the code in your function from the beginning until it hits yield , then it'll return the first value of the loop.

(for第一次调用从您的函数创建的生成器对象时,它将从头开始运行函数中的代码,直到达到yield为止,然后它将返回循环的第一个值。)

Then, each other call will run the loop you have written in the function one more time, and return the next value until there is no value to return.

(然后,每次其他调用将再次运行您在函数中编写的循环,并返回下一个值,直到没有值可返回为止。)

The generator is considered empty once the function runs, but does not hit yield anymore.

(函数运行后,该生成器将被视为空,但不再达到yield 。)

It can be because the loop had come to an end, or because you do not satisfy an "if/else" anymore.

(可能是因为循环已经结束,或者是因为您不再满足"if/else" 。)


Your code explained (您的代码说明)

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

This code contains several smart parts:

(该代码包含几个智能部分:)

  • The loop iterates on a list, but the list expands while the loop is being iterated :-) It's a concise way to go through all these nested data even if it's a bit dangerous since you can end up with an infinite loop.

    (循环在列表上迭代,但是在循环时列表扩展:-)这是浏览所有这些嵌套数据的一种简洁方法,即使这样做有点危险,因为您可能会遇到无限循环。)

    In this case, candidates.extend(node._get_child_candidates(distance, min_dist, max_dist)) exhaust all the values of the generator, but while keeps creating new generator objects which will produce different values from the previous ones since it's not applied on the same node.

    (在这种情况下, candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))耗尽了生成器的所有值,但while继续创建新的生成器对象,该对象将产生与先前值不同的生成器,因为它没有应用在相同的值上节点。)

  • The extend() method is a list object method that expects an iterable and adds its values to the list.

    (extend()方法是一个列表对象方法,该方法需要可迭代并将其值添加到列表中。)

Usually we pass a list to it:

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

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

But in your code, it gets a generator, which is good because:

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

  1. You don't need to read the values twice.

    (您无需两次读取值。)

  2. You may have a lot of children and you don't want them all stored in memory.

    (您可能有很多孩子,并且您不希望所有孩子都存储在内存中。)

And it works because Python does not care if the argument of a method is a list or not.

(它之所以有效,是因为Python不在乎方法的参数是否为列表。)

Python expects iterables so it will work with strings, lists, tuples, and generators!

(Python期望可迭代,因此它将与字符串,列表,元组和生成器一起使用!)

This is called duck typing and is one of the reasons why Python is so cool.

(这就是所谓的鸭子输入,这是Python如此酷的原因之一。)

But this is another story, for another question...

(但这是另一个故事,还有另一个问题...)

You can stop here, or read a little bit to see an advanced use of a generator:

(您可以在这里停止,或者阅读一点以了解生成器的高级用法:)

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

Note: For Python 3, use print(corner_street_atm.__next__()) or print(next(corner_street_atm))

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

It can be useful for various things like controlling access to a resource.

(对于诸如控制对资源的访问之类的各种事情,它可能很有用。)

Itertools, your best friend (Itertools,您最好的朋友)

The itertools module contains special functions to manipulate iterables.

(itertools模块包含用于操纵可迭代对象的特殊功能。)

Ever wish to duplicate a generator?

(曾经希望复制一个发电机吗?)

Chain two generators?

(连锁两个发电机?)

Group values in a nested list with a one-liner?

(用一个单行将嵌套列表中的值分组?)

Map / Zip without creating another list?

(Map / Zip而未创建其他列表?)

Then just import itertools .

(然后只需import itertools 。)

An example?

(一个例子?)

Let's see the possible orders of arrival for a four-horse race:

(让我们看一下四马比赛的可能到达顺序:)

>>> horses = [1, 2, 3, 4]
>>> races = itertools.permutations(horses)
>&g

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...