# Python notes - Day10 - iterator generator and module

2022-05-15 06:03:23

Preface
python Grammar learning , Leave it to those who need it , Understand everything ！！

``````# coding=utf8
# @time:2022/4/19 20:56
# Author  Haoyu

#  One 、 iterator
# 1. What is iterator （）
'''''''''
1） Iterators are container data types
2） The iterator cannot get all the elements directly , You can only take one by one （ Taking an iterator means taking it out , And I can't get in or out ）; I can't get through len Number of statistical elements
3） Method for creating iterators ：a. Replace other sequences with iterators
b. generator
'''''''''
'''''''''
list1=[1,20,4,56]
print(list1)    # [1, 20, 4, 56]
print(len(list1))   # 4

i1 = iter(list1)
print(i1,type(i1))  # <list_iterator object at 0x0000029522C71220> <class 'list_iterator'>
'''''''''
# printe(len(i1)) #  Iterators cannot pass len Number of Statistics

# 2. Get elements
#  It doesn't matter how you get the elements in the iterator , Then this element does not exist in the iterator
'''''''''
1） Get a single element
next( iterator )

give an example ：
list2=[11,20,4,56]
i2 = iter(list2)
print(next(i2)) # 11
print(next(i2)) # 20

2） Traverse
for  Variable  in  iterator ：
The loop body

give an example ：
i3 = iter(range(5))
for x in i3:
print(f'x:{x}')
'''''''''

#  Two 、 generator
# 1. What is a generator （generator）
'''''''''
1） Perceptual knowledge
Generator is a special iterator
The generator can be understood as a machine that produces data , When storing, the algorithm that generates the data is saved, not the data itself
2） Rational knowledge
Call with yield Keyword function can get a generator
( If a function has yield, Then calling this function will not execute the function body , Nor does it get the return value . The value of the function call expression is a generator object )
grammar ：

'''''''''
# 2. How to create a generator
'''''''''
def func1():
yield
print('====')
return 100

func1()
result = func1()    # result It's a generator
print(result)
'''''''''

# 3. How to determine the ability of the generator to generate data
'''''''''
1） How many data can be created ？ What are they? ？
a. After executing the function corresponding to the generator, you will encounter several times yield, So how many data can this generator create
b. Every encounter yield,yield What is the following value , What is the corresponding created data

give an example 1：
def func2():
yield 10
yield 100
yield 1000

gen1 = func2()
print(next(gen1))   # 10
print(next(gen1))   # 100
print(next(gen1))   # 1000
——————————————————————————————————————
give an example 2：
def func3():
for x in range(5):
yield x**10

gen2 = func3()
for x in gen2:
print(f'x:{x}')
# x:0
# x:1
# x:1024
# x:59049
# x:1048576
'''''''''

# 4. How the generator generates data
#  The function corresponding to the generator will not execute the function body when calling the function , The function body is executed only when the data in the generator is obtained
#  Every time you get data , The function body is executed from the last end position , Until I met yield Just stop , take yield The following data is returned as a result , And record the end position
#  If it is next selection , When executing, if you encounter the end of the function, you don't encounter yield You're going to report a mistake ！
'''''''''
#  give an example ：
def func4():
print('===1===')
yield 10
print('===2===')
yield 20
print('===3===')
yield 30
print('===4===')
yield 40
print('===end===')

gen3 = func4()
print(' For the first time ：',next(gen3))
print(' The second value is ：',next(gen3))
print(' The third value ：',next(gen3))
print(' The fourth value ：',next(gen3))
# print(' The fifth value ：',next(gen3))
'''''''''

'''''''''
#  practice ：
#  practice 1： Write a generator that can generate a student number with a specified prefix and a specified length ？
#  Prefix ：py, length ：4 py001~py9999
# 4 - 1~9999;10**4-1
# 3 - 1~999 ;10**3-1
# 2 - 1~99 ;10**2-1
def create_study_num(pre,length):
for x in range(1,10**length):
result = pre+str(x).zfill(length)
yield result

nums = create_study_num('py',4)
print(next(nums))
print(next(nums))
print(next(nums))
'''''''''

#  3、 ... and 、 modular
# 1. What is a module
#  A module is a file that contains all the functions and variables you define , Its suffix is .py

# 2. How to use the content of another module in one module
'''''''''
Be careful ： If a module wants to be used by other modules , Then the module must meet the requirements of identifier when naming
One module wants to use the content in another module , Must import first ：
1）import  Module name     -    Be able to use all global variables in the module ; Use it by ” Module name .“ The way
2）from  Module name  import  Variable name 1, Variable name 2,...     -    Be able to use the variables specified in the module ; Variables directly use
3） Module renaming ：import  modular  as  New module name
4） Variable rename ：from  modular  import  Variable  as  Variable number name
5） Import all variables ：from  Module name  import *
'''''''''

# 1） The first way to import ：import
# import test
# print(test.x)
# test.test_func()

# 2） The second import method ：from ... import ...
# from test import x,test_func
# print(x)
# test_func()

# 3） The third import method ： Module renaming
# import test as TS -  Put the original test Module renamed to TS

# 4） The fourth import rename method ： Variable rename
# from test import x as y -  Put the original test Module x Rename it to y

# 5） wildcard *
# from test import * -  hold test All variables in the module are imported

# 3. Principle of import module
#  principle ：
# a. When the code is executed into the import module , The system will automatically execute all the codes in the imported module
``````

More secure sharing , Please pay attention to 【 Security info】 WeChat official account ！