We can create a list simply and directly through list generation, but due to memory constraints, the list capacity is definitely limited. Moreover, creating a list containing 1 million elements not only takes up a lot of storage space, but if we only need to access the first few elements, the space occupied by most of the subsequent elements is wasted.
So, if the list elements can be calculated according to a certain algorithm, can we continuously calculate subsequent elements during the loop? This eliminates the need to create a complete list, saving a lot of space. In Python, this mechanism of looping and calculating at the same time is called a generator.
To create a generator, there are many ways. The first method is very simple. Just change the [] of a list generation expression to () to create a generator:
>>> mylist = [ x for x in range(1, 10)] >>> mylist [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> gen = (x for x in range(1,10)) >>> gen <generator object <genexpr> at 0x7f1d7fd0f5a0>
The difference between creating mylist and gen is only the outermost [] and ( ), mylist is a list, and gen is a generator.
We can directly print out each element of the list, but how do we print out each element of the generator?
If you want to print them out one by one, you can use the next() method of the generator:
>>> gen.next() 1 >>> gen.next() 2 >>> gen.next() 3 ... >>> gen.next() 9 >>> gen.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
We have said that the generator saves the algorithm. Each time next() is called, the value of the next element is calculated. , until the last element is calculated and there are no more elements, a StopIteration error is thrown.
In fact, we can use for loop instead of next() method, which is more in line with efficient programming ideas:
>>> gen = ( x for x in range(1, 10)) >>> for num in gen: ... print num ... 1 2 3 4 5 6 7 8 9
generator is very powerful. If the calculation algorithm is relatively complex and cannot be implemented using a for loop similar to list generation, you can also use a function to implement it.
For example, in the famous Fibonacci sequence, except for the first and second numbers, any number can be obtained by adding the first two numbers:
1, 1, 2, 3, 5, 8, 13, 21, 34, ...
Fi The Boracchi sequence cannot be written using list generation, but it is easy to print it out using a function:
def fib(max): n = 0 a, b = 0, 1 while n < max: print b a, b = b, a + b n = n + 1
The above function can output the first N numbers of the Fibonacci sequence:
>>> fib(6) 1 1 2 3 5 8
If you look closely, you can see that the fib function actually defines the calculation rules of the Fibonacci sequence. It can start from the first element and calculate any subsequent elements. This logic is actually very similar to the generator.
In other words, the above function is only one step away from the generator. To turn the fib function into a generator, just change print b to yield b:
def fib(max): n = 0 a, b = 0, 1 while n < max: yield b a, b = b, a + b n = n + 1
This is another way to define a generator. If a function definition contains the yield keyword, then the function is no longer an ordinary function, but a generator:
>>> fib(6) <generator object fib at 0x104feaaa0>
Here, the most difficult thing to understand is that the execution flow of generator and function is different. Functions are executed sequentially and return when encountering a return statement or the last line of function statements. The function that becomes a generator is executed every time next() is called, returns when encountering a yield statement, and continues execution from the yield statement returned last time when executed again.
As a simple example, define a generator that returns the numbers 1, 3, and 5 in sequence:
>>> def odd(): ... print 'step 1' ... yield 1 ... print 'step 2' ... yield 3 ... print 'step 3' ... yield 5 ... >>> o = odd() >>> o.next() step 1 1 >>> o.next() step 2 3 >>> o.next() step 3 5 >>> o.next() Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration
You can see that odd is not an ordinary function, but a generator. During execution, it encounters It will be interrupted when yield is reached and execution will continue next time. After executing yield three times, there is no more yield to execute, so an error is reported when next() is called for the fourth time.
Back to the fib example, if we keep calling yield during the loop, it will continue to be interrupted. Of course, you need to set a condition for the loop to exit the loop, otherwise an infinite number will be listed.
Similarly, after changing the function to a generator, we basically never use next() to call it, but directly use a for loop to iterate:
>>> for n in fib(6): ... print n ... 1 1 2 3 5 8
generator is a very powerful tool, In Python, you can simply change the list generation into a generator, or you can use functions to implement complex logic generators.
To understand the working principle of the generator, it continuously calculates the next element during the for loop and ends the for loop under appropriate conditions. For a generator changed from a function, when the return statement is encountered or the last line of the function body is executed, it is the instruction to end the generator, and the for loop ends accordingly.

Python and C each have their own advantages, and the choice should be based on project requirements. 1) Python is suitable for rapid development and data processing due to its concise syntax and dynamic typing. 2)C is suitable for high performance and system programming due to its static typing and manual memory management.

Choosing Python or C depends on project requirements: 1) If you need rapid development, data processing and prototype design, choose Python; 2) If you need high performance, low latency and close hardware control, choose C.

By investing 2 hours of Python learning every day, you can effectively improve your programming skills. 1. Learn new knowledge: read documents or watch tutorials. 2. Practice: Write code and complete exercises. 3. Review: Consolidate the content you have learned. 4. Project practice: Apply what you have learned in actual projects. Such a structured learning plan can help you systematically master Python and achieve career goals.

Methods to learn Python efficiently within two hours include: 1. Review the basic knowledge and ensure that you are familiar with Python installation and basic syntax; 2. Understand the core concepts of Python, such as variables, lists, functions, etc.; 3. Master basic and advanced usage by using examples; 4. Learn common errors and debugging techniques; 5. Apply performance optimization and best practices, such as using list comprehensions and following the PEP8 style guide.

Python is suitable for beginners and data science, and C is suitable for system programming and game development. 1. Python is simple and easy to use, suitable for data science and web development. 2.C provides high performance and control, suitable for game development and system programming. The choice should be based on project needs and personal interests.

Python is more suitable for data science and rapid development, while C is more suitable for high performance and system programming. 1. Python syntax is concise and easy to learn, suitable for data processing and scientific computing. 2.C has complex syntax but excellent performance and is often used in game development and system programming.

It is feasible to invest two hours a day to learn Python. 1. Learn new knowledge: Learn new concepts in one hour, such as lists and dictionaries. 2. Practice and exercises: Use one hour to perform programming exercises, such as writing small programs. Through reasonable planning and perseverance, you can master the core concepts of Python in a short time.

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version
Recommended: Win version, supports code prompts!

SublimeText3 Chinese version
Chinese version, very easy to use

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software