当前位置:网站首页>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()
边栏推荐
- PHP programming language (1) - operators
- Rhsca day 11 operation
- Article publishing experiment
- /*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*/
- Reasons and solutions for the 8-hour difference in mongodb data date display
- Recursion and divide and conquer strategy
- OSPF summary
- RHCE day 3
- Doris / Clickhouse / Hudi, a phased summary in June
- Write a program to judge whether the elements contained in a vector < int> container are 9.20: exactly the same as those in a list < int> container.
猜你喜欢

Occasional pit compiled by idea

MPLS: multi protocol label switching

The most detailed teaching -- realize win10 multi-user remote login to intranet machine at the same time -- win10+frp+rdpwrap+ Alibaba cloud server

How to use diff and patch to update the source code

Rhcsa learning practice

DNS hijacking

Introduction to extensible system architecture

C language structure to realize simple address book

Two way process republication + routing policy

system design
随机推荐
OSPF summary
Rhcsa12
[advantages and disadvantages of outsourcing software development in 2022]
Sword finger offer 05 (implemented in C language)
Recursion and divide and conquer strategy
Doris / Clickhouse / Hudi, a phased summary in June
PHP programming language (1) - operators
Recursive method to achieve full permutation (C language)
2020-03-28
Safety reinforcement learning based on linear function approximation safe RL with linear function approximation translation 1
[Galaxy Kirin V10] [server] failed to start the network
如果不知道這4種緩存模式,敢說懂緩存嗎?
C language structure to realize simple address book
20 minutes to learn what XML is_ XML learning notes_ What is an XML file_ Basic grammatical rules_ How to parse
Velodyne configuration command
[Galaxy Kirin V10] [desktop] FTP common scene setup
Tables in the thesis of latex learning
Two way process republication + routing policy
Latex learning insertion number - list of filled dots, bars, numbers
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