Want to improve sầu this post? Provide detailed answers to this question, including citations & an explanation of why your answer is correct. Answers without enough detail may be edited or deleted.
What is the use of the yield từ khoá in Python? What does it do?

For example, I"m trying lớn underst& this code1:

def _get_child_candidates(self, distance, min_dist, max_dist): if self._leftchild và distance - max_dist = self._median: yield self._rightchild And this is the caller:

result, candidates = <>, while candidates: node = candidates.pop() distance = node._get_dist(obj) if distance = min_dist: result.extend(node._values) candidates.extend(node._get_child_candidates(distance, min_dist, max_dist))return resultWhat happens when the method _get_child_candidates is called?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 Pyhẹp library for metric spaces. This is the liên kết khổng lồ the complete source: <1>.
pyhẹp iterator generator yield coroutine
Share
Improve sầu this question
Follow
edited Jun 12 at 19:47
*

BuddyBob
5,60311 gold badge88 silver badges2929 bronze badges
asked Oct 23 "08 at 22:21
*

Alex. S.Alex. S.
129k1717 gold badges5050 silver badges6161 bronze badges
1
Add a comment |

40 Answers 40


Active Oldest Votes
1
2 Next
16201
+600
To understand what yield does, you must understand what generators are. And before you can underst& generators, you must underst& iterables.

Bạn đang xem:

Iterables

When you create a menu, you can read its items one by one. Reading its items one by one is called iteration:

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

Generators

Generators are iterators, a kind of iterable you can only iterate over once. Generators bởi not store all the values in memory, they generate the values on the fly:

Yield

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

To master yield, you must understand that when you Gọi the function, the code you have written in the function body toàn thân does not run. 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.

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. Then, each subsequent Hotline will run another iteration of the loop you have sầu written in the function & return the next value. This will continue until the generator is considered empty, which happens when the function runs without hitting yield. That can be because the loop has come to an over, or because you no longer satisfy an "if/else".

Xem thêm: Tìm Hiểu Các Công Nghệ Màn Hình Cảm Ứng Đa Điểm Là Gì, Cảm Ứng Đa Điểm

Your code explained

Generator:

# Here you create the method of the node object that will return the generatordef _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 và 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 & the right childrenCaller:

# Create an empty các mục và a list with the current object referenceresult, candidates = list(), # Loop on candidates (they contain only one element at the beginning)while candidates: # Get the last candidate và remove sầu it from the danh sách node = candidates.pop() # Get the distance between obj & the candidate distance = node._get_dist(obj) # If distance is ok, then you can fill the result if distance = min_dist: result.extend(node._values) # Add the children of the candidate in the candidate"s menu # 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 resultThis code contains several smart parts:

The loop iterates on a list, but the danh mục expands while the loop is being iterated. It"s a concise way khổng lồ go through all these nested data even if it"s a bit dangerous since you can over 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.

The extend() method is a các mục object method that expects an iterable và adds its values lớn the các mục.

Usually we pass a list khổng lồ it:

You don"t need to lớn read the values twice.You may have a lot of children và you don"t want them all stored in memory.

And it works because Pynhỏ nhắn does not care if the argument of a method is a list or not. Pyhạn hẹp expects iterables so it will work with strings, lists, tuples, and generators! This is called duchồng typing and is one of the reasons why Pynhỏ bé is so cool. But this is another story, for another question...

You can stop here, or read a little bit khổng lồ see an advanced use of a generator:

Controlling a generator exhaustion

It can be useful for various things like controlling access lớn a resource.

Itertools, your best friend

The itertools module contains special functions khổng lồ manipulate iterables. Ever wish lớn duplicate a generator?Chain two generators? Group values in a nested list with a one-liner? Map / Zip without creating another list?

Then just import itertools.

Xem thêm: Ông Nguyễn Lân Trung Là Ai, Vì Sao Bị Gọi Là Kẻ Ăn Hôi Vĩ Đại Việt Nam

An example? Let"s see the possible orders of arrival for a four-horse race:

Understanding the inner mechanisms of iteration

Iteration is a process implying iterables (implementing the __iter__() method) & iterators (implementing the __next__() method).Iterables are any objects you can get an iterator from. Iterators are objects that let you iterate on iterables.


Chuyên mục: Blogs