当前位置:网站首页>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()
边栏推荐
- Work order management system OTRs
- 按键精灵跑商学习-商品数量、价格提醒、判断背包
- BGP ---- border gateway routing protocol ----- basic experiment
- [Galaxy Kirin V10] [desktop] can't be started or the screen is black
- Snake (C language)
- [Galaxy Kirin V10] [server] iSCSI deployment
- If you don't know these four caching modes, dare you say you understand caching?
- [Galaxy Kirin V10] [desktop] build NFS to realize disk sharing
- PHP code audit 3 - system reload vulnerability
- 2022 ape circle recruitment project (software development)
猜你喜欢

DNS hijacking

Basic data types of MySQL

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

Evolution from monomer architecture to microservice architecture

Three schemes of ZK double machine room

183 sets of free resume templates to help everyone find a good job

Realsense of d435i, d435, d415, t265_ Matching and installation of viewer environment

MPLS: multi protocol label switching

Article publishing experiment
![[Galaxy Kirin V10] [desktop] can't be started or the screen is black](/img/68/735d80c648f4a8635513894c473860.jpg)
[Galaxy Kirin V10] [desktop] can't be started or the screen is black
随机推荐
Dichotomy search (C language)
Rhcsa - day 13
Doris / Clickhouse / Hudi, a phased summary in June
[FAQ] summary of common causes and solutions of Huawei account service error 907135701
Ruby time format conversion strftime MS matching format
On binary tree (C language)
Delayed message center design
[test theory] test process management
2022 ape circle recruitment project (software development)
Number of relationship models
Introduction to extensible system architecture
Today's sleep quality record 78 points
Basic data types of MySQL
Add t more space to your computer (no need to add hard disk)
Uniapp--- initial use of websocket (long link implementation)
Realsense d435 d435i d415 depth camera obtains RGB map, left and right infrared camera map, depth map and IMU data under ROS
/*Write a loop to output the elements of the list container in reverse order*/
[Galaxy Kirin V10] [desktop] build NFS to realize disk sharing
If the uniapp is less than 1000, it will be displayed according to the original number. If the number exceeds 1000, it will be converted into 10w+ 1.3k+ display
[Galaxy Kirin V10] [server] KVM create Bridge