当前位置:网站首页>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()
边栏推荐
- From programmers to large-scale distributed architects, where are you (2)
- leetcode842. Split the array into Fibonacci sequences
- Basic data types of MySQL
- Four characteristics and isolation levels of database transactions
- What is devsecops? Definitions, processes, frameworks and best practices for 2022
- Press the button wizard to learn how to fight monsters - identify the map, run the map, enter the gang and identify NPC
- The most detailed teaching -- realize win10 multi-user remote login to intranet machine at the same time -- win10+frp+rdpwrap+ Alibaba cloud server
- /*Write a loop to output the elements of the list container in reverse order*/
- [Galaxy Kirin V10] [server] grub default password
- Introduction to extensible system architecture
猜你喜欢

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

shell awk

C language - stack

The time difference between the past time and the present time of uniapp processing, such as just, a few minutes ago, a few hours ago, a few months ago
![[Galaxy Kirin V10] [server] NFS setup](/img/ed/bd7f1a1e4924a615cb143a680a2ac7.jpg)
[Galaxy Kirin V10] [server] NFS setup

For programmers, if it hurts the most...

20 minutes to learn what XML is_ XML learning notes_ What is an XML file_ Basic grammatical rules_ How to parse

Introduction to extensible system architecture

VI text editor and user rights management, group management and time management

Rhcsa learning practice
随机推荐
Latex error: missing delimiter (. Inserted) {\xi \left( {p,{p_q}} \right)} \right|}}
Recursion and divide and conquer strategy
[Galaxy Kirin V10] [server] set time synchronization of intranet server
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
What is an excellent architect in my heart?
Write a program to define an array with 10 int elements, and take its position in the array as the initial value of each element.
Sword finger offer 05 (implemented in C language)
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?
MPLS: multi protocol label switching
Leetcode48. Rotate image
Network disk installation
[machine] [server] Taishan 200
【Day2】 convolutional-neural-networks
Rhcsa operation
Time complexity and space complexity
BGP advanced experiment
183 sets of free resume templates to help everyone find a good job
Huge number multiplication (C language)
Write a program that uses pointers to set all elements of an int array to 4.18: 0.