current position：Home>Python iterators and generators
Python iterators and generators
2022-01-30 17:46:24 【LolitaAnn】
Little knowledge , Great challenge ！ This article is participating in “ A programmer must have a little knowledge ” Creative activities .
Once I was a front-end student, I finally took the postgraduate entrance examination , I thought I got rid of it js, result python There is also an iterator generator , Out of line .
Usually we use for The cycle is smooth and easy, isn't it . such as
What's the principle ？
forStatement is called on the container object
iter(). This function returns a definition
__next__()Iterator object for method , This method will access the elements in the container one by one . When the elements are exhausted ,
__next__()Will lead to
StopIterationException to notify termination
forloop . You can use
next()Built in function to call
Below we see iterator Yes, it is a The list generates an iterator , Every time you call next Will take one a The elements in .
When you write next When the number of elements is exceeded, there will be StopIteration Abnormal stop .
With a yield The function of is a generator, It's different from ordinary functions , Generate a generator It looks like a function call , But no function code is executed , Until you call next()（ stay for It's called automatically in the loop next()） Just started to execute .
Because I don't learn python Someone who looks directly at the code , I met generator today .
I am here indices There's a whole print(indices), Then call the function in a decent way data_iter(...), The results cannot be printed no matter how they are run or debugged indices, Until I see yield I don't feel good about it ……
Although the execution process still follows the process of the function , But every time it gets to one yield The statement breaks , And return an iteration value , The next execution is from yield Continue with the next statement of . It looks like a function is being yield Several interruptions , Every interrupt passes yield Returns the current iteration value .
yield The benefits are obvious , Rewrite a function to a generator And you get the ability to iterate , Instead of saving the state of a class instance to calculate the next next() Value , Not only is the code concise , And the execution process is extremely clear .
At the end of function execution ,generator Automatically throw out StopIteration abnormal , Indicates that the iteration is complete . stay for In circulation , No need to deal with StopIteration abnormal , The cycle will end normally .
Like a function call , But it's generating a generator ：
yield Action image of return equally , Use next Call generator , Every time the generator executes to yield Throw a return value to stop execution , Until next time next Since the last time yield Continue where you stop , Throw until the iteration object runs out StopIteration Abnormal termination .
Add two small knowledge
How to judge whether a function is generator？ If your eyes are OK, you should be able to see yield Of . If you're looking for a way to be tall , That can be used ：
from inspect import isgeneratorfunction isgeneratorfunction( Function name ) Copy code
If so, the generator will return true
yield image return, that generator You can have return Do you ？
In a generator function in , without return, The default execution is until the function is finished , If in the course of execution return, And just throw it out StopIteration Termination iteration .
author[LolitaAnn],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Python notes (6): definition and use of lists
- Python notes (V): string operation
- Python notes (IV): use of functions and modules
- Python notes (3): conditional statements and circular statements
- Python notes (II): lexical structure
- Notes on python (I): getting to know Python
- [Python data structure series] - tree and binary tree - basic knowledge - knowledge point explanation + code implementation
- [Python daily homework] Day7: how to combine two dictionaries in an expression?
- How to implement a custom list or dictionary in Python
- 15 advanced Python tips for experienced programmers
guess what you like
Python string method tutorial - how to use the find() and replace() functions on Python strings
Python computer network basics
Python crawler series: crawling global airport information
Python crawler series: crawling global port information
How to calculate unique values using pandas groupby
Application of built-in distribution of Monte Carlo simulation SciPy with Python
Gradient lifting method and its implementation in Python
Pandas: how to group and calculate by index
Can you create an empty pandas data frame and fill it in?
Python basic exercises teaching! can't? (practice makes perfect)
- Exploratory data analysis (EDA) in Python using SQL and Seaborn (SNS).
- Turn audio into shareable video with Python and ffmpeg
- Using rbind in python (equivalent to R)
- Pandas: how to create an empty data frame with column names
- Talk about quantifying investment using Python
- Python, image restoration in opencv - CV2 inpaint
- Python notes (14): advanced technologies such as object-oriented programming
- Python notes (13): operations such as object-oriented programming
- Python notes (12): inheritance such as object-oriented programming
- Chapter 2: Fundamentals of python-5 Boolean
- Python notes (11): encapsulation such as object-oriented programming
- Python notes (10): concepts such as object-oriented programming
- Gradient lifting method and its implementation in Python
- Van * Python | simple crawling of a site course
- Chapter 1 preliminary knowledge of pandas (list derivation and conditional assignment, anonymous function and map method, zip object and enumerate method, NP basis)
- Nanny tutorial! Build VIM into an IDE (Python)
- Fourier transform of Python OpenCV image processing, lesson 52
- Introduction to python (III) network request and analysis
- China Merchants Bank credit card number recognition project (Part I), python OpenCV image processing journey, Part 53
- Introduction to python (IV) dynamic web page analysis and capture
- Python practice - capture 58 rental information and store it in MySQL database
- leetcode 119. Pascal's Triangle II（python）
- leetcode 31. Next Permutation（python）
- [algorithm learning] 807 Maintain the city skyline (Java / C / C + + / Python / go / trust)
- The rich woman's best friend asked me to write her a Taobao double 11 rush purchase script in Python, which can only be arranged
- Glom module of Python data analysis module (1)
- Python crawler actual combat, requests module, python realizes the full set of skin to capture the glory of the king
- Summarize some common mistakes of novices in Python development
- Python libraries you may not know
- [Python crawler] detailed explanation of selenium from introduction to actual combat 
- This is what you should do to quickly create a list in Python
- On the 55th day of the journey, python opencv perspective transformation front knowledge contour coordinate points
- Python OpenCV image area contour mark, which can be used to frame various small notes
- How to set up an asgi Django application with Postgres, nginx and uvicorn on Ubuntu 20.04
- Initial Python tuple
- Introduction to Python urllib module
- Advanced Python Basics: from functions to advanced magic methods
- Python Foundation: data structure summary
- Python Basics: from variables to exception handling
- Python notes (22): time module and calendar module