Table of Contents
yield 与 return" >yield 与 return
生成器支持的方法(借鉴别人的例子,感觉蛮好的)" >生成器支持的方法(借鉴别人的例子,感觉蛮好的)
close()" >close()
send()" >send()
执行流程:" >执行流程:
throw()" >throw()
执行流程:" >执行流程:
Home Backend Development Python Tutorial Introduction and use of Python generators

Introduction and use of Python generators

Jul 19, 2017 pm 11:25 PM
python Summarize

The generator in python saves the algorithm, and the value will be calculated only when the value is really needed. It is a lazy evaluation.

There are two ways to create a generator.

The first method: Change [] in a list generation expression to () to create a generator:

>>> L = [x * x for x in range(10)]>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]>>> g = (x * x for x in range(10)) # Note that after changing [] to (), instead of generating a tuple, a generator>>> g at 0x1022ef630>

Second way: Use the yield keyword in the function, and the function becomes a generator.

After there is yield in the function, the execution will stop when yield is reached, and the calculation will be continued when further calculation is needed. So it doesn't matter even if the generator function has an infinite loop, it will calculate as much as it needs to count, and it won't continue counting if it doesn't need to.

def fib():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
f = fib()
print f, next(f), next(f), next(f)
# 0 1 1

As in the above example, when f is output for the first time, it is a generator, and every time next is executed, it will be executed to yield a.

Of course, next() is rarely used. We can directly use a for loop to traverse a generator. In fact, the internal implementation of the for loop is to continuously call next().

The generator can avoid unnecessary calculations and improve performance; it also saves space and can realize infinite loop (infinite) data structures.

Generator syntax
Generator expression: The same as list parsing syntax, but replace the [] of list parsing with ()
What generator expressions can do List parsing can basically handle things, but when the sequence to be processed is relatively large, list parsing consumes more memory.

Generator function: If the yield keyword appears in a function, then the function is no longer an ordinary function, but a generator function.

In Python, yield is such a generator.

The operating mechanism of the yield generator:

When you ask the generator for a number, the generator will execute until the yield statement appears, and the generator will The parameters are given to you, and then the generator will not continue to run. When you ask him for the next number, he will start from the last state. Start running until the yield statement appears, give you the parameters, and then stop. This is repeated until the function exits.

Use of yield:

In Python, when you define a function and use the yield keyword, the function is a generator, and its execution will be the same as other ordinary functions. There are many differences. The function returns an object, instead of getting the result value like the return statement you usually use. If you want to get the value, you have to call the next() function

Take Fibonacci as an example:

#coding:utf8
def fib(max): #10
    n, a, b = 0, 0, 1
    while n < max: #n<10
        #print(b)
        yield b
        a, b = b, a + b

        n += 1
    return 

f = fib(10)
for i in f:
    print f
Copy after login

From the above description of the operating mechanism, we can know that when the program reaches the yield line, it will not continue to execute. Instead, it returns an iterator object containing the status of all parameters of the current function. The purpose is to be able to access all the parameter values ​​of the function when it is called for the second time, instead of reassigning them.

When the program is called for the first time:

def fib(max): #10
    n, a, b = 0, 0, 1
    while n < max: #n<10
        #print(b)
        yield b   #这时a,b值分别为0,1,当然,程序也在执行到这时,返回
        a, b = b, a + b
Copy after login

程序第二次调用时:

从前面可知,第一次调用时,a,b=0,0,那么,我们第二次调用时(其实就是调用第一次返回的iterator对象的next()方法),程序跳到yield语句处,

执行a,b = b, a+b语句,此时值变为:a,b = 0, (0+1) => a,b = 0, 1

程序继续while循环,当然,再一次碰到了yield a 语句,也是像第一次那样,保存函数所有参数的状态,返回一个包含这些参数状态的iterator对象。

等待第三次的调用....

通过上面的分析,可以一次类推的展示了yield的详细运行过程了!

通过使用生成器的语法,可以免去写迭代器类的繁琐代码,如,上面的例子使用迭代类来实现,代码如下:

#coding:UTF8

class Fib:  
    def __init__(self, max):  
        self.max = max
        print self.max
    def __iter__(self):  
        self.a = 0  
        self.b = 1 
        self.n = 0 
        return self  
    def next(self):  
        fib = self.n  
        if fib >= self.max:  
            raise StopIteration  
        self.a, self.b = self.b, self.a + self.b  
        self.n += 1
        return self.a
    
f = Fib(10)
for i in f:
    print i
Copy after login

yield 与 return

在一个生成器中,如果没有return,则默认执行到函数完毕时返回StopIteration;

如果遇到return,如果在执行过程中 return,则直接抛出 StopIteration 终止迭代。

如果在return后返回一个值,会直接报错,生成器没有办法使用return来返回值。

生成器支持的方法(借鉴别人的例子,感觉蛮好的)

     close(...)
 |      close() -> raise GeneratorExit inside generator.
 |  
 |  next(...)
 |      x.next() -> the next value, or raise StopIteration
 |  
 |  send(...)
 |      send(arg) -> send &#39;arg&#39; into generator,
 |      return next yielded value or raise StopIteration.
 |  
 |  throw(...)
 |      throw(typ[,val[,tb]]) -> raise exception in generator,
 |      return next yielded value or raise StopIteration.
Copy after login

close()

手动关闭生成器函数,后面的调用会直接返回StopIteration异常。

#coding:UTF8

def fib():
    yield 1
    yield 2
    yield 3

f = fib()
print f.next()
f.close()
print f.next()
Copy after login

send()

生成器函数最大的特点是可以接受外部传入的一个变量,并根据变量内容计算结果后返回。
这是生成器函数最难理解的地方,也是最重要的地方,

def gen():
    value=0
    while True:
        receive=yield value
        if receive==&#39;e&#39;:
            break
        value = &#39;got: %s&#39; % receive
 
g=gen()
print(g.send(None))     
print(g.send(&#39;aaa&#39;))
print(g.send(3))
print(g.send(&#39;e&#39;))
Copy after login

执行流程:

  1. 通过g.send(None)或者next(g)可以启动生成器函数,并执行到第一个yield语句结束的位置。此时,执行完了yield语句,但是没有给receive赋值。yield value会输出初始值0注意:在启动生成器函数时只能send(None),如果试图输入其它的值都会得到错误提示信息。

  2. 通过g.send(‘aaa’),会传入aaa,并赋值给receive,然后计算出value的值,并回到while头部,执行yield value语句有停止。此时yield value会输出”got: aaa”,然后挂起。

  3. 通过g.send(3),会重复第2步,最后输出结果为”got: 3″

  4. 当我们g.send(‘e’)时,程序会执行break然后推出循环,最后整个函数执行完毕,所以会得到StopIteration异常。

最后的执行结果如下:

0
got: aaa
got: 3
Traceback (most recent call last):
  File "1.py", line 15, in <module>
    print(g.send(&#39;e&#39;))
StopIteration
Copy after login

 

throw()

用来向生成器函数送入一个异常,可以结束系统定义的异常,或者自定义的异常。
throw()后直接跑出异常并结束程序,或者消耗掉一个yield,或者在没有下一个yield的时候直接进行到程序的结尾。

def gen():
    while True: 
        try:
            yield &#39;normal value&#39;
            yield &#39;normal value 2&#39;
            print(&#39;here&#39;)
        except ValueError:
            print(&#39;we got ValueError here&#39;)
        except TypeError:
            break
 
g=gen()
print(next(g))
print(g.throw(ValueError))
print(next(g))
print(g.throw(TypeError))
Copy after login

执行流程:

  1. print(next(g)):会输出normal value,并停留在yield ‘normal value 2’之前。

  2. 由于执行了g.throw(ValueError),所以会跳过所有后续的try语句,也就是说yield ‘normal value 2’不会被执行,然后进入到except语句,打印出we got ValueError here。然后再次进入到while语句部分,消耗一个yield,所以会输出normal value。

  3. print(next(g)),会执行yield ‘normal value 2’语句,并停留在执行完该语句后的位置。

  4. g.throw(TypeError):会跳出try语句,从而print(‘here’)不会被执行,然后执行break语句,跳出while循环,然后到达程序结尾,所以跑出StopIteration异常。

  

 

The above is the detailed content of Introduction and use of Python generators. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Can vs code run in Windows 8 Can vs code run in Windows 8 Apr 15, 2025 pm 07:24 PM

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

Can visual studio code be used in python Can visual studio code be used in python Apr 15, 2025 pm 08:18 PM

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

How to run programs in terminal vscode How to run programs in terminal vscode Apr 15, 2025 pm 06:42 PM

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

Is the vscode extension malicious? Is the vscode extension malicious? Apr 15, 2025 pm 07:57 PM

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

See all articles