current position:Home>Python notes - Day10 - iterator generator and module
Python notes - Day10 - iterator generator and module
2022-05-15 06:03:23【Wandering mage 12】
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 !
copyright notice
author[Wandering mage 12],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/131/202205110607424507.html
The sidebar is recommended
- Introduction to the differences between Python and Java
- Explain Python CONDA in detail
- The pycham downloaded by MAC reports an error as soon as it is opened. The downloaded Python interpreter is also the latest version
- From entry to mastery, python full stack engineers have personally taught Python core technology and practical combat for ten years
- Python is used to detect some problems of word frequency in English text.
- How to choose between excel, database and pandas (Python third-party library)?
- WxPython download has been reporting errors
- Pyside6 UIC and other tools cannot be found in the higher version of pyside6 (QT for Python 6). How to solve it?
- About Python Crawlers
- Successfully imported pandas, unable to use dataframe
guess what you like
How to extract some keywords in the path with Python
Python encountered a problem reading the file!
When Python is packaged into exe, an error is reported when opening assertionerror: C: \ users \ Acer \ appdata \ local \ temp\_ MEI105682\distutils\core. pyc
Eight practical "no code" features of Python
Python meets SQL, so a useful Python third-party library appears
100 Python algorithm super detailed explanation: a hundred dollars and a hundred chickens
[fundamentals of Python] Python code and so on
When Python uses probit regression, the program statement is deleted by mistake, and then it appears_ raise_ linalgerror_ Unrecognized error of singular
Python testing Nicholas theorem
Accelerating parallel computing based on python (BL) 136
Random recommended
- Python dynamic programming (knapsack problem and longest common substring)
- Django uses queryset filter save, and an 'queryset' object has no attribute 'Save' error occurs. Solution?
- Analysis of built-in functions in Python learning
- Python office automation - 90 - file automation management - cleaning up duplicate files and batch modifying file names
- Python office automation - 91 - word file Automation - word operation and reading word files
- After python, go also runs smoothly on the browser
- Self taught Python 26 method
- Summary of Python Tkinter component function examples (code + effect picture) (RadioButton | button | entry | menu | text)
- Python implementation of official selection sorting of Luogu question list
- Application of Django template
- Get project root path and other paths in Python project
- Get, rename, and delete file names in Python projects
- How to set the width and height of Python operation table
- Python string preceded by 'f' R 'B' U '
- JSON and other types convert to each other in Python
- Key value of key combination in pynput in Python
- Conversion of Python PDF file to word file
- Interface testing uses Python decorators
- Get the current time in Python
- Python course notes -- Python string, detailed explanation of related functions
- Python file and folder operations
- Python file content operation
- Three basic data quality evaluation methods and python implementation
- Python data structure and mathematical algorithm examples (continuously updating)
- GUI interface mail sending program based on SMTP protocol server and python language
- Python application tool development: mail sending GUI program
- Python application tool development: PIP instruction GUI program
- Application development based on Python and MySQL database: student information score management system version 1.0
- [Python] sort and sorted
- [Python] create a two-dimensional array with list, which is easy to step on
- Multiply [email protected]
- About creating in Python project folder__ init__. Understanding of PY
- Python, zsbd
- Smplify introduction and in python2 7 operation in environment
- Boost(2):boost. Python library introduction and simple examples
- Boost (3): encapsulate C + + classes into Python classes
- Boost (5): extract the type of C + + language and extract class from Python object
- Boost(6):Boost. How Python converts C + + parameter and return value types
- Boost(7):Boost. Python encapsulates overloaded functions and passes default parameters
- Boost(8):Boost. Python implements Python objects and various types of built-in operations and methods