当前位置:网站首页>8. iterators and generators
8. iterators and generators
2022-06-25 20:04:00 【Iron plate jumping to the bottom】
1 Iteratable objects and iterators
- What is iterator
Iteration is the renewal
1.1. Iterators are tools for iterating values
1.2. Iteration is a repetitive process , Each repetition is based on the results of the previous one
such as : The father gave birth to a son , The son gave birth to a grandson
1. The first development project , Internet company
The basic functions are realized in the front , Ensure the number of users
It can be changed slowly later , Improve quality
2. The teacher's first class , nervous , Technical difficulties , The first time is impossible
That's perfect , But slowly improve , It's also an iterative process
3. The students have one point of knowledge that they don't understand , Like decorators
Perfect doesn't have to give up , master @+ The name of the decorator is ok
Learning is also an iterative process , It is based on the results of the last study
Once understood 60%, Next time I'll see what happens 80%, Use of the 100%.
4. First time in love , It can't be perfect , It is also a process of gradual improvement - Why use iterators
Tools are tools
Iterators provide a general and index independent function of iterating - How to use iterators
1.2. Iteration is a repetitive process , Each repetition is based on the results of the previous one
l = ['a','b','c']
#0 1 2
i = 0
while i < len(l):
print(l[i])
i += 1
The data to be iterated are :
character string 、 list 、 Tuples 、 Dictionaries 、 aggregate 、 Documents, etc.
Iteratable object iterable
Everything has ".iter()" Method objects are called gram iteration objects
a=[1,2,3]
iter_a = a.__iter__() # Generate iterators
iter_a .__next__() # next Methods that do not depend on index values
Iteratable objects and iterators
Iteratable object
Only __iter__ Method , No, __next__ Method
iterator
1. It's built-in __next__ Object of method , Executing iterators __next__ Methods can be independent of index values
2. And built in __iter__ Object of method , Executing iterators __iter__ Method still gets the iterator itself
An iterator can be generated by a single object
dic={'x':1,'y':2,'z':3}
# At the bottom
iter_dic=dic.__iter__()
next_dic =iter_dic.__next__()
# Built in method
iter_dic1 = iter(dic)
next_dic1 = next(iter_dic1)
Iterator summary
advantage :
- It provides a general and index independent iterative method
- There is only one value in memory at the same time , More memory saving
shortcoming :
- It is not as flexible as indexing ,( Cannot take a specified value , And you can only take it back )
- The length of the iterator cannot be predicted
2 generator
The big premise : A generator is a custom iterator , The essence is iterators
Whenever a function contains yield keyword , The calling function does not execute the function body code
Will get a return value , The return value is the generator object
def func():
print('======1')
yield 1 # Every time __next__() Go to pause
print('======2')
yield 2 # Every time __next__() Go to pause
g=func()
print(g.__next__())
print(g.__next__())
summary yield: Can only be used within a function
- yield Provides a solution for customizing iterators
- yield You can save the suspended state of the function
- yield contrast return
- The same thing : Can return a value , There is no limit to the type and number of values
- Difference :yield Can return multiple values ( Pause ), and return The function that can only return a value once ends ( end )
Define a generator , This generator can generate 10 Bit fiboracci sequence , Get the fiboracci sequence
( Fibonacci sequence : The value of each number in the sequence is equal to the sum of the first two numbers [1, 1, 2, 3, 5, 8, 13, 21, 34, 55…])
def run(n):
i , a, b = 0,1,1
while i < n:
yield a# # a The first is the a 1 b 1 The second time a 1 b 2 third time a 2 b 3 The fourth time a 3 b 5 The fifth time a 5 b 8
a , b = b ,a+b
i+=1
my_run=run(10)
print(my_run)
print(list(my_run))
print(' Custom iterators ( generator ) Of for loop ')# 1 Start 4 Start Old hen
for i in my_run:
print(i)
print(' Custom iterators ( generator ) Of for loop ')# 1 Start 4 Start Old hen
for i in my_run:
print(i)
3 Generator calculation hierarchy
Use a generator to calculate 1!+2!+3!+4!+…10! And
Stratum
1! = 1
2! = 2X1
3! = 3X2X1
4! = 4X3X2X1
Count variables i
Stratum j
def func(n): # n The class of
i = 1# Count variables for the first time i 1
j = 1
while i <= n:
yield j# for the first time j 1
i += 1# The count is self increasing 1 The second time i 2 third time i 3 The fourth time i 4 The first 5 Time i 5
j = j * i# The second time j 2 third time j 1*2 * 3 = 6 The fourth time j 1 *2 * 3 * 4 = 24 The first 5 Time 1 *2 * 3 * 4 * 5
a=func(10)
边栏推荐
- Applet password input box
- 2.17(Avoid The Lakes)
- PAT B1071
- Huawei in application review test requirements
- 2020-12-09 laravel . Env file loading mechanism process
- Database data type design (the most detailed in the whole network)
- My official account writing experience sharing
- Yaml configuration
- Redis practice: smart use of data types to achieve 100 million level data statistics
- Dependency injection in PHP reflection implementation framework
猜你喜欢

PAT B1086

Two types of attribute injection methods

Now meditation: crash service and performance service help improve application quality

DARKHOLE 2

Web components - Basics

Yaml configuration

New features of redis 6.0: take you 100% to master the multithreading model

My official account writing experience sharing

H5 application conversion fast application

<C>. Figure guessing game
随机推荐
Suddenly found that the screen adjustment button can not be used and the brightness can not be adjusted
Does redis transaction support acid?
wooyun-2014-065513
Thymleaf template configuration analysis
Jsonp non homologous interaction (click trigger)
Validation of TTF font by validator of laravel
JS get the parameters in the URL link
Print 1 cute every 100 milliseconds ~ with a running lantern effect
Panda weekly -2022/02/18
<C>. Calculation date to day conversion
Yum command
Appearance of object attributes
PAT B1059
The native JS mobile phone sends SMS cases. After clicking the button, the mobile phone number verification code is sent. The button needs to be disabled and re enabled after 60 seconds
PAT B1051
String since I can perform performance tuning, I can call an expert directly
PostgreSQL change table owner
Applet Click to return to the top 2 methods
Uni app through uni Navigateto failed to pass parameter (pass object)
PAT B1061