Iterator (iter)
Iterator definition
- Iterators are container data types that can store multiple data at the same time; It can be traversed or converted into lists and tuples;
- The elements in the iterator cannot be displayed and printed when printing; Iterator does not support len operation;
- If the element in the iterator is needed, the element must be taken out of the iterator, and once the element is taken out, the element in the iterator does not exist;
Create iterator
-
Convert other sequences into iterators through iter;
-
Create the generator object (the generator can be regarded as a special iterator);
iter1 = iter('abc') print(iter1) # <str_iterator object at 0x000001F1C03E4B20> # print(len(iter1)) # TypeError: object of type 'str_iterator' has no len()
Gets the element in the iterator
- Get single element - next (iterator)
- When there is no element in the iterator, an error will be reported when using the next function, StopIteration
- for loop traversal
iter1 = iter('abc') print(next(iter1)) # a print(next(iter1)) # b print(next(iter1)) # c # print(next(iter1)) iter2 = iter([10, 20, 30, 40]) for x in iter2: print(f'x:{x}') iter3 = iter('hello') print(list(iter3)) # ['h', 'e', 'l', 'l', 'o'] elements have been fetched # print(next(iter3)) # An error is reported because there are no elements
Generator
Generator definition
-
The generator is a container capable of generating multiple data;
-
The generator is the same as the iterator when obtaining data;
Create generator
-
Call a function with yieid keyword to get a generator object;
-
If yieid is in a function, the function will not execute the function body or get the return value when calling, but get a generator;
def func1(): print('===') print('+++') result1 = func1() print(result1) # === +++ None def func2(): print('===') yield print('+++') result2 = func2() print(result2) # <generator object func2 at 0x000001776D748350>
Generator data generation
- Executing the function corresponding to the generator will encounter yieid several times. How many data can be generated by the generator, and the value after yieid is the corresponding data that can be generated;
# Data will be generated several times, and the following value is the return value def func31(): yield 100 for i in range(4): yield i for x in func31(): print('===', x) """-------------------------------""" def func32(): yield 100 yield 200 yield 300 # Only the generator will be created continuously, and then the first available data will be obtained print(next(func32())) # 100 print(next(func32())) # 100 print(next(func32())) # 100 # After obtaining the generator with variables, you can obtain the data of the generator one by one gen3 = func32() print(next(gen3)) # 100 print(next(gen3)) # 200 print(next(gen3)) # 300 """-------------------------------""" # Exercise 1: create a generator that produces the first N even numbers def get_even(num): for even in range(0, num * 2, 2): yield even # even = 0 # for _ in range(num): # yield even # even += 2 gen_get_even = get_even(5) for x in gen_get_even: print(x)
How the generator generates data
-
When the data is obtained through the generator object, the program will execute the function corresponding to the generator;
-
Every time yieid is encountered, it will stop, take the data behind yieid as the data obtained this time, and record the end position;
-
The next time data is obtained, it is directly executed from the last end position;
def func4(): print('-' * 10, '1', '-' * 10) yield 100 print('-' * 10, '2', '-' * 10) yield 200 print('-' * 10, '3', '-' * 10) yield 300 print('-' * 10, 'end', '-' * 10) gen5 = func4() print(gen5) # <generator object func4 at 0x000001E12EC7D4A0> print('Take element:', next(gen5)) print('Other code can be executed') print('Take element:', next(gen5)) print('Take element:', next(gen5)) # print('Take element:', next(gen5)) # StopIteration, because there is no yieid at the end of the function body gen1 = (i for i in range(0, 20, 2)) print(gen1)
modular
- In Python, a py file is a module;
Use of modules
-
Note: if a module can be used by other modules, the file name of the module must be an identifier and not a keyword;
-
After the module is imported, the module can use all global variables in the imported module;
Import module
- import module name
- Import the specified module, which can be imported through "module name." Method to use all global variables of the module.
- import module name as new module name - Rename module
- When a variable in the module repeatedly conflicts with the imported module name, the imported module can be renamed in this way;
- from module name import global variable 1, global variable 2,..., global variable N
- Import the specified module. After importing, you can directly use the specified global variables
- from module name import*
- Import the specified module, and all global variables can be used;
- from module name import global variable 1 as new global variable 1, global variable 2
- If the variable name conflicts, you can rename the specified variable without affecting other imported variables;
# # Import method 1 import test_import print(test_import.a) print(test_import.x) # # Import method 2 from test_import import a print(a) # # Import method 3 from test_import import * print(a) print(x) print(func1()) # # Import method 4 - Rename module import test_import as test1 test_import = 1 test1.func1() # Import method 5 - Rename variables from test_import import a as a1, x print(a1) print(x)
Principle of import module
- When importing a module through import or from import, the system will automatically execute all the codes in the module;
# import test_import from test_import import a
- PY file imported
print('-------------start---------------') a = 100 def downland1(): print('1') print('2') print('3') def func1(): print('func1') print('-------------end---------------') # The code in this if statement will not be executed when imported by other modules. It will only be executed when the current meter is running directly if __name__ == '__main__': for x in range(5): print('x:', x) downland1()
Use of packages
What is a bag
- A package contains__ init__.py file folder;
Import modules from the package (using the contents of the package)
- import package name
- Import package directly
- import package modular
- You can use "package. Module. Variable" to use all global variables in the specified module
- from package import module 1, module 2
- from package Module import module contents (global variables)
# 2.1 direct import package import package # 2.2 import module through package import package.json package.json.read_json() # 2.3 import and rename modules through packages import package.json as packjson packjson.read_json() # 2.4 importing modules through packages from package import excel, json excel.read_excel() json.read_json() # 2.5 import the contents of the module through the package from package.json import read_json read_json()
How to import packages
- When importing modules in the package through the package, the program will execute the modules in the package first__ init__.py file, and then execute the code in the corresponding module;
In__ init__.py to create shortcut keys for some methods
# First in__ init__.py imports some contents of the package once from package.excel import read_excel - stay__init__.py in from package import read_excel # Then import the corresponding content in other places where these contents are used read_excel()
In__ init__. Encapsulating general functions or data in PY
- Some common contents or methods in this package, such as opening and closing files;