python13. Iterators and generators and packages are positive

1. Inferred expressions
Inferred expressions, also called analytical expressions, are a unique feature of Python. A deduction is a structure that can construct a new data sequence from one data sequence, which can simplify sentences by a large margin, but it is also more prone to errors. So to understand its structural logic, there are three derivations:

  • List comprehension
  • Dictionary comprehension
  • Set comprehension

1. List comprehension

Introduce a question, how to get a list with elements from 0 to 9?

According to the basic knowledge of Python learned before, it can be done like this:

Now, we can achieve this function through a more concise statement of list comprehension:

In contrast, the first form of loop iteration uses three lines of code, while the second form of list comprehension uses one line of code.

How can we write list comprehensions if we add conditional judgments based on the list cycle? The title is a list with elements from 0 to 9. Find out which elements are even numbered?

Here if is mainly used for conditional judgment, only those that meet the if condition will be left, and finally a data list will be uniformly generated. The print result of code execution is: [0, 2, 4, 6, 8].

Here if...else mainly plays the role of assignment. When the if condition is met, the i code will be processed, otherwise the i*10 code will be processed, and finally a data list will be uniformly generated.

2. Dictionary comprehension

The use of dictionary deduction and list deduction is similar, except that the square brackets should be changed to braces:

In addition, let's take another example of how to convert a list into a dictionary and obtain key-value pairs:

3. Set comprehension

The use of set comprehension and list comprehension is similar, the only difference is that it uses curly braces {}:

The result of executing this code is: {1,4}.

Summary: Compared with the for loop to process data, the deduction expression is more convenient for code conciseness, but it is better to use the for loop at present. When the code proficiency is high, master the basic Python grammar and be more comfortable with the code before making extensive use of deduction. formula.

Two, iterator

Iterator refers to a tool for iterating values. Iteration refers to a process of repetition. Each repetition is based on the previous result. It is one of the most powerful features of Python and is a way to access collection elements. And iteration provides a universal iterative method that does not rely on indexes.

1. Why use iterators

Use for loop to traverse sequence objects (str, list, tuple), sequence objects have indexes, and members of sequence objects can be accessed through indexes. When using a for loop to traverse a sequence object, you can use the index of the sequence object to traverse, or you can use the sequence item to traverse. When the for loop uses the sequence item to traverse the object, an iterator is used. In addition, Python also has data that is not a sequence object, such as collections, dictionaries, files, etc. How to traverse the members of these data types, this also requires the use of iterators.

2. Iterable objects

Any object with a built-in __iter__ method is called an iterable object, an iterable object: sequence objects include lists, tuples and strings, non-sequence objects include dictionaries, collections, and files, and implement __iter__ and _ The custom object of the _next__ method is also an iterable object.

3. Iterator object

  • Objects with both built-in and __next__ methods, the method can be executed without relying on index values

  • There is also an object with the __iter__ method built in, and the __iter__ method of the iterator is still the iterator itself.

The iterator object is accessed from the first element of the collection until all the elements have been accessed. The iterator can only go forward and not go backward. There are two basic methods for iterators: iter() and next().

An iterator must be an iterable object, and an iterable object is not necessarily an iterator object. The file object itself is an iterator object. The following examples can be used to deeply understand this conclusion.

4. Generate an iterator and take a value

String, list or tuple objects can all be used to create iterators:

Executing this code, the result is:

Summarize the usage of the iterator and next() above:

Generate an iterator from the iterable object: iterator=iter(iterable object), next value=next(iterator).

5. Handwritten iterator (just understand)

Can iterable objects and iterators be customized? Is there an easy way to customize it?

  • 1. Add the __iter__ method to the class to get the iterator.
  • 2. Point out all the data through the __next__ method.

Three, the generator

1. Why use a generator?

In Python, the mechanism of calculating while looping is called a generator. We know that we can use lists to store data, but when our data is particularly large, the storage of data to create a list will take up a lot of memory. Then the generator comes in handy. It can be said to be a method that does not occupy much computer resources. In a nutshell: I want to get huge amounts of data, but also want to make it take up less space, then use a generator!

2. Create a generator

  • Changing the [] of a list comprehension to () creates a generator.

  • If a function contains the yield keyword, then this function is no longer an ordinary function, but a generator. Calling a function creates a generator object.

3. Principle of generator

The key to the generator's ability to iterate is that it has a next() method, which works by repeatedly calling the next() method until an exception is caught. When taking a value in the generator, basically you will not use next() to get the next return value, but directly use the for loop to iterate).

Below, let's take a look at a simple case:

Executing this code, the result is:

Any function with a yield statement is a generator. When you call this function directly, the internal code will not be executed. Only by calling the next function in the yield will the code be executed, and the for loop will automatically To call the next function to output the value. It can be understood that a function is interrupted by yield. When the download is called again, it continues to execute the code from the position where it was interrupted and returns the value.

1), the role of the yield keyword

  • Save the current running state (breakpoint), and then suspend execution, that is, suspend the generator (function);
  • Return the value of the expression after the yield keyword as the return value, which can be understood as a return;
  • You can use the next() function to let the generator continue execution from the breakpoint, that is, wake up the generator (function);
  • When the iteration encounters yield, it returns the value behind or to the right of yield. And in the next iteration, the code after the yield encountered in the previous iteration starts to execute.
    Below, learn a more in-depth case:

Executing this code, the result is:

The key to understanding is: in the next iteration, the code starts to execute from the next statement of yield.

2), send() method

In addition to using the next() function to wake up the generator to continue execution, we can also use the send() function to wake up execution. One advantage of using the send() function is that you can pass additional data to the breakpoint while waking up.

The difference between send() and next() is that send can pass parameters to the yield expression. At this time, the passed parameters will be used as the value of the yield expression, and the yield parameter is the value returned to the caller, that is to say, send You can forcibly modify the value of the previous yield expression.

To understand the send() method through a simple example:

Executing this code, the result is:

Talk about the order of execution. First, a() is a generator; the first execution is either next® or r.send(None), r.send('xxxxx') cannot be used; this will report an error. When next® is executed for the first time, aaa is printed first,

Then it jumps out when it encounters yield, and then executes r.send('hello'), p1 is assigned to hello, and then continues with the last run, the next step is to print out bbb, and then print out'p1 is passed by send ', when the second yield is encountered again, it jumps out, so the result is only three lines printed, and the following p2 is not executed.

Fourth, the module

1. Module definition

In the previous chapters, we used the python interpreter to program the script. If you exit from the Python interpreter and then enter, all the methods and variables you defined will disappear.

For the project, the program file will not appear in one file, so it is necessary to group many functions with similar functions and put them in different files, and use the file name to distinguish the general function of each file. For this reason, Python provides a way to store these definitions in a file for use by some scripts or interactive interpreter instances. This file is called a module.

A module is a file that contains all the functions and variables you define, and its suffix is ​​.py. Modules can be introduced by other programs to use functions and other functions in the module. This is also the way to use the python standard library.

2. Module advantages

  • Modules are used to improve the maintainability of the code
  • Can improve code reusability
  • To reference other modules, including built-in modules [provided by Python] and third-party modules and custom modules
  • Can avoid the conflict of function name and variable name

3. Import module method

__name__ is displayed as an execution command when calling its own file, and the file name is displayed when calling other files

  • import

Import can be followed by a module or multiple modules, such as import os, time, sys, re, etc., each module is separated by a comma; importing a module is actually executing a py file; opening up a new content, Load content into memory.

  • from…import

When we use a module, we may only want to use some of the functions. For example, when we only want to use the modules in the sys module, then import is not easy to use. At this time, we can use the format from...import to carry out the module. Import of a certain function. Such as:

import sys.module: This is a demonstration of the wrong import module;
from sys import modules: This is the correct import form.

from...import also supports as mode, such as:

from sys import modules as md: means to abbreviate modules as md.

  • from…import *

The asterisk means that all names in the imported module that do not start with an underscore (_) are imported to the current position. In most cases, our python program should not use this import method, because *you don’t know what name you import, it’s very It may overwrite the name you have previously defined. And the readability is extremely poor, there is no problem when importing in an interactive environment.

Specification suggestion: Modules should be imported one by one, the order is: built-in module---->extended (third-party) module---->custom module;

Order description: We know that importing a module is actually executing this module. We are not sure whether a function in the extension module or custom module calls the built-in module, so when we import the module, we should first import the built-in module of the interpreter , And then import the extension module, and finally import the custom module.

The following is an example of using modules in the python standard library.

To view the source code of the imported module, you can use the shortcut key: Ctrl+mouse to draw on this module. There are many python standard libraries, you can check the information outside of class to understand. The import case of the custom module is explained in detail in the next section "Package and Package Management".

Five, package and package management

1. Package definition

In order to better manage multiple module source files, Python provides the concept of packages. So the question is, what is a package?

From the physical point of view, the package is a folder contains a folder in which the init .py file folder comprising a plurality of modules may be used to source files; Logically, the nature of the package is still module. Therefore, the syntax of importing packages and importing modules is exactly the same

2. Steps to create a package:

  • 1. Create a folder named package name
  • 2. Create an __init__.py file in this folder
  • 3. Store script files, compiled extensions and sub-packages in this folder as needed.
  • 4、import pack.m1

For example: create a pack of folders, which create m1.py, text.py, the init .py, __init__.py file containing the folder was called as a package. Then, if text.py needs to call the content of m1 of pack, text.py should write:

3. Example of calling between modules in the same directory

Create a directory pack, and place two modules in the directory: m1.py is used to store custom functions, and text.py is used to call functions in the m1.py module and output test results. Note that the __init__.py file is not placed in the pack directory this time.

Execute text.py, the printing result is: 3.

In addition to directly importing the entire module, you can also selectively import: from m1 import jia, this import mode is also possible.

Pay attention to the difference between these two methods: After directly importing the entire module, Python uses the module name as a pointer to the imported module (PS: it can be considered that the module name variable saves the address of the imported module after it is loaded into the memory), so every call is The module name needs to be prefixed. The way to import part of the content of the module is to use the name of the specific content of the imported module (such as function name, variable name) as a pointer to the imported part of the content, so you can directly use the function name and variable name. In summary, whoever is imported will be recognized by this module.

4. Example of calling between cross-directory modules

Create a new directory pack1 under pack, place the text.py file in the root directory, and place m1.py and __init__.py under pack1.

Executing this code, the result is: 3.
Of course, the management of packages and modules under windows is far from that simple. For the time being, we know how to call custom packages and modules.

Guess you like

Origin blog.csdn.net/qwe863226687/article/details/113969130