当前位置:网站首页>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

  1. 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
  2. Why use iterators
    Tools are tools
    Iterators provide a general and index independent function of iterating
  3. 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 :

  1. It provides a general and index independent iterative method
  2. There is only one value in memory at the same time , More memory saving

shortcoming :

  1. It is not as flexible as indexing ,( Cannot take a specified value , And you can only take it back )
  2. 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

  1. yield Provides a solution for customizing iterators
  2. yield You can save the suspended state of the function
  3. yield contrast return
    1. The same thing : Can return a value , There is no limit to the type and number of values
    2. 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)
原网站

版权声明
本文为[Iron plate jumping to the bottom]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202190508572563.html