About Generator

孔棋
2023-12-01
Generators are relatively new to Python, and are (along with iterators) perhaps one of the most powerful features to come along for years.
The following example is a function that flattens nested lists.
def flatten(nested):
       for sublist in nested:
             for element in sublist:
                   yield element

nested = [[1, 2], [3, 4], [5]]
>>> flatten(nested)
<generator object flatten at 0x924d93c>
>>> list(flatten(nested))
[1, 2, 3, 4, 5]
So what's new here is the yield statement. Any function that contains a yield statement is called a generator.  The difference between normal function and generator is that instead of returning one value, as you do with return, you can yield several values, one at a time. Each time a value is yielded (with yield), the function freezes;  that is, it stops its execution at exactly that point and waits to be reawakened. When it is, it resumes its execution at the point where it stopped. Finally the generator function will return a generator object which contain all the yielded values and you can use some function to process the object, like list().
 类似资料:

相关阅读

相关文章

相关问答