当前位置:网站首页>Iterator generators and modules
Iterator generators and modules
2022-07-04 10:39:00 【She was your flaw】
Iterator generators and modules
One 、 iterator
What is iterator (iter)
Iterators are container data types , Multiple data can be saved at the same time , Can be traversed ; It can also be converted into lists and tuples
When printing an iterator, you cannot print the elements inside ; Iterator not supported len operation
If you need elements in the iterator , You must take the element out of the iterator , And once the element is taken out , This element does not exist in the iterator .
How to create iterators
Method 1 : adopt iter Replace other sequences with iterators
Method 2 : Create a generator object ( Generator can be regarded as a special iterator )
iter1 = iter('abc')
print(iter1)
# print(len(iter)) # Report errors !
Get the elements in the iterator
1) Get a single element :next( iterator )
2)for Loop traversal
print(next(iter1)) # 'a'
print(next(iter1)) # 'b'
print(next(iter1)) # 'c'
# print(next(iter1)) # Report errors !
for x in iter1:
print(f'x:{
x}')
iter2 = iter([10, 20, 30, 40])
for x in iter2:
print(f'x:{
x}')
# print(next(iter2)) # StopIteration
iter3 = iter('hello')
print(list(iter3)) # ['h', 'e', 'l', 'l', 'o']
# print(next(iter3)) # Report errors !
Two 、 generator
generator (generator)
A generator is a container with the ability to generate multiple data .
Generators are the same as iterators when getting data .
How to create a generator
Call a with yield Keyword function can get a generator object
( If a function has yield, Then this function will not execute the function body when calling , Nor does it get the return value , And get a generator )
def func1():
print('=====')
print('+++++')
if False:
yield
result = func1()
print('result', result)
Control the ability of the generator to generate data
Executing the function corresponding to the generator will encounter several times yield How many data can this generator generate , Every encounter yield When ,yield The following values correspond to the data that can be generated .
def func2():
yield 100
for i in range(4):
yield i
gen2 = func2()
for x in gen2:
print (f'====:{
x}')
def func3():
yield 100
yield 200
yield 300
print(next(func3()))
print(next(func3()))
print(next(func3()))
gen3 = func3()
print(next(gen3))
print(next(gen3))
print(next(gen3))
practice 1: Create a generator function , Can be produced before N An even number , Even from 0 Start
N -> 5 produce :0, 2, 4, 6, 8
def nums_creater(n: int):
nums = 0
for i in range(0, 2*x, 2):
yield i
nums += 2
gen4 = nums_creater(5)
print(next(gen4))
for x in gen4:
print(x)
How the generator generates data
When getting data through the generator object , The program will execute the function corresponding to the generator , Only execute until yield Will stop , take yield The following data is taken as the data obtained this time , Record the end position , The next time you get data, start from the last end .
def func4():
print('-------1---------')
yield 100
print('-------2---------')
yield 200
print('-------3---------')
yield 300
print('-------end---------')
gen5 = func4()
print(gen5)
print(' Take the element :', next(gen5))
for _ in range(5):
print('+++++++')
print(' De element :', next(gen5))
print(' De element :', next(gen5))
# print(' De element :', next(gen5)) # Report errors !
3、 ... and 、 modular
What is a module
python In a py File is a module
How to use the content of another module in one module
Be careful : If you want a module to be used by another module , Then the module name of this module must be an identifier and And not a keyword
One module can use all global variables in another module , But you must import before usingThe import module
import Module name – Import the specified module , Import can be done through ’ Module name .' Use all global variables in the module
form Module name import Global variables 1, Global variables 2,… - Import the specified module , After importing, you can directly use the specified global variables
from Module name import * – Import the specified module , After importing, you can directly use all global variables
import Module name as New module name – Rename the module , Use the new module name when using the module after renaming
from Module name import Variable name as New variable name – Rename the imported variable
Import method 1 :
import test1
print(test1.a) # 10
print(test1.x) # 100
test1.func1() # test1 Function of
Import mode 2 :
from test1 import x, func1
print(x) # 100
func1() # test1 Function of
Import mode 3 : Use wildcards *
from test1 import *
print(a)
print(x)
func1()
Import mode 4 : Module renaming
import test1 as test
test1 = 300
print(test1) # 300
print(test.a, test.x) # 10 100
test.func1() # test1 Function of
Import method 5 : Rename the variable
from test1 import a as a1, x, func1
a = 'abc'
print(a) # abc
print(a1) # 10
print(x) # 100
func1() # test1 Function of
Principle of import module
When passed import perhaps from-import When importing a module , The system will automatically execute all the codes in this module
import test1
from test1 import a
Four 、 Use of the bag
What is a bag
A package contains (init.py) File folder
Use the contents of the package ( Import )
import Package name – Direct import package
import Package name . modular – Can pass ’ package . modular ’ Use all global variables in the specified module
from package import modular 1, modular 2, …
from package . modular import Variable name 1, Variable name 2,…
The principle of importing packages
When importing modules in the package through the package , The program will execute in the package first __init__.py All the codes in the file , Then execute the code in the corresponding module .
1. Direct import package
import files
2. Import modules through packages
import files.excel
files.excel.read_excel()
print(files.excel)
3. rename
import files.excel as f_excel
f_excel.read_excel()
print(f_excel.x)
4. Import modules through packages
from files import excel, plist
excel.read_excel()
plist.read_plist()
5. Import the contents of the module through the package
from files.excel import read_excel
read_excel()
6. Directly use the shortcuts in the package
import files
files.read_excel()
from files import read_excel
read_excel()
import files
files.plist.read_plist()
import files
files.open_file()
边栏推荐
- [untitled]
- Huge number multiplication (C language)
- OSPF comprehensive experiment
- BGP ---- border gateway routing protocol ----- basic experiment
- uniapp---初步使用websocket(长链接实现)
- Leetcode48. Rotate image
- DDL language of MySQL database: create, modify alter, delete drop of databases and tables
- BGP advanced experiment
- Recursion and divide and conquer strategy
- Application and Optimization Practice of redis in vivo push platform
猜你喜欢
Rhcsa12
system design
BGP ---- border gateway routing protocol ----- basic experiment
[Galaxy Kirin V10] [desktop] build NFS to realize disk sharing
[Galaxy Kirin V10] [server] FTP introduction and common scenario construction
183 sets of free resume templates to help everyone find a good job
Basic principle of servlet and application of common API methods
On binary tree (C language)
Rhcsa - day 13
MPLS: multi protocol label switching
随机推荐
[Galaxy Kirin V10] [server] NFS setup
Rhsca day 11 operation
Press the button wizard to learn how to fight monsters - identify the map, run the map, enter the gang and identify NPC
Using SA token to solve websocket handshake authentication
Work order management system OTRs
Jianzhi offer 04 (implemented in C language)
The bamboo shadow sweeps the steps, the dust does not move, and the moon passes through the marsh without trace -- in-depth understanding of the pointer
Rhcsa operation
/*Rewrite the program, find the value of the element, and return the iterator 9.13: pointing to the found element. Make sure that the program works correctly when the element you are looking for does
Application and Optimization Practice of redis in vivo push platform
PHP programming language (1) - operators
[Galaxy Kirin V10] [desktop] FTP common scene setup
Network disk installation
How to quickly parse XML documents through C (in fact, other languages also have corresponding interfaces or libraries to call)
Write a program that uses pointers to set all elements of an int array to 4.18: 0.
Button wizard business running learning - commodity quantity, price reminder, judgment Backpack
Two way process republication + routing policy
[Galaxy Kirin V10] [desktop] build NFS to realize disk sharing
Today's sleep quality record 78 points
[Galaxy Kirin V10] [desktop] can't be started or the screen is black