当前位置:网站首页>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()
边栏推荐
- OSPF summary
- Static comprehensive experiment ---hcip1
- Add t more space to your computer (no need to add hard disk)
- Container cloud notes
- Sword finger offer 31 Stack push in and pop-up sequence
- Network connection (II) three handshakes, four waves, socket essence, packaging of network packets, TCP header, IP header, ACK confirmation, sliding window, results of network packets, working mode of
- The most detailed teaching -- realize win10 multi-user remote login to intranet machine at the same time -- win10+frp+rdpwrap+ Alibaba cloud server
- 【Day2】 convolutional-neural-networks
- Legion is a network penetration tool
- Service developers publish services based on EDAs
猜你喜欢
Safety reinforcement learning based on linear function approximation safe RL with linear function approximation translation 1
Number of relationship models
Network connection (III) functions and similarities and differences of hubs, switches and routers, routing tables and tables in switches, why do you need address translation and packet filtering?
Doris / Clickhouse / Hudi, a phased summary in June
shell awk
The most detailed teaching -- realize win10 multi-user remote login to intranet machine at the same time -- win10+frp+rdpwrap+ Alibaba cloud server
VLAN part of switching technology
[Galaxy Kirin V10] [desktop] cannot add printer
For programmers, if it hurts the most...
What is an excellent architect in my heart?
随机推荐
[test theory] test the dimension of professional ability
Recursive method to achieve full permutation (C language)
【Day2】 convolutional-neural-networks
DML statement of MySQL Foundation
Uniapp--- initial use of websocket (long link implementation)
Talk about scalability
The last month before a game goes online
Quick sort (C language)
MFC document view framework (relationship between classes)
Rhcsa day 9
TS type gymnastics: illustrating a complex advanced type
Summary of several job scheduling problems
/*The rewriter outputs the contents of the IA array. It is required that the type defined by typedef cannot be used in the outer loop*/
[Galaxy Kirin V10] [server] system startup failed
Write a program that uses pointers to set all elements of an int array to 4.18: 0.
[Galaxy Kirin V10] [server] FTP introduction and common scenario construction
Service developers publish services based on EDAs
Number of relationship models
[Galaxy Kirin V10] [desktop] login system flash back
[untitled]