The authors introduce :【 Lonely and cold 】—CSDN High quality creators in the whole stack field 、HDZ Core group members 、 Huawei cloud sharing expert Python Full stack domain bloggers 、CSDN The author of the force program
- This article has been included in Python Full stack series column :《Python Full stack basic tutorial 》
- Popular column recommendation :《Django Framework from the entry to the actual combat 》、《 A series of tutorials from introduction to mastery of crawler 》、《 Reptile advanced 》、《 Front end tutorial series 》、《tornado A dragon + A full version of the project 》.
- This column is for the majority of program users , So that everyone can do Python From entry to mastery , At the same time, there are many exercises , Consolidate learning .
- After subscribing to the column But there are more than 1000 people talking privately Python Full stack communication group ( Teaching by hand , Problem solving ); Join the group to receive Python Full stack tutorial video + Countless computer books : Basics 、Web、 Reptiles 、 Data analysis 、 visualization 、 machine learning 、 Deep learning 、 Artificial intelligence 、 Algorithm 、 Interview questions, etc .
- Join me to learn and make progress , One can walk very fast , A group of people can go further !
Maybe many friends who read my previous articles will say , I have already talked about it in detail in the previous articles ? Why is there another article about !
As the saying goes , Important things are to be repeated for 3 times , And what I want to say is , Important Python We should talk more about the knowledge points !
meanwhile , This article has come to a new and important knowledge point —— generator !
Iteration is Python One of the most powerful features , Is a way to access collection elements .
An iterator is an object that remembers the location of the traversal .
The iterator object is accessed from the first element of the collection , Until all the elements are accessed , Iterators can only move forward and not backward .
What kind of process is iteration ?
Generally, a new list is constructed in this way :
# -*- coding: utf-8 -*-
""" __author__ = Lonely and cold """
li = []
for i in range(1,10):
li.append(i)
print(li) # Output is :[1, 2, 3, 4, 5, 6, 7, 8, 9]
List derivation :
li1 = [i for i in range(1,10)]
print(li1) # Output is :[1, 2, 3, 4, 5, 6, 7, 8, 9]
( You can also use it range(1,10,2)
li3 = [i for i in range(1,10) if i % 2 !=0]
print(li3) # Output is :[1, 3, 5, 7, 9]
# -*- coding: utf-8 -*-
""" __author__ = Lonely and cold """
li4 = [(i,j) for i in range(1,5) for j in range(1,5)]
print(li4) # Output is : [(1, 1), (1, 2), (1, 3), (1, 4),
# (2, 1), (2, 2), (2, 3), (2, 4),
# (3, 1), (3, 2), (3, 3), (3, 4),
# (4, 1), (4, 2), (4, 3), (4, 4)]
Set derivation :
li5 = {
i for i in range(1,10)}
print(li5) # Output is :{1, 2, 3, 4, 5, 6, 7, 8, 9}
Dictionary derivation :
li6 = {
i:j for i in range(1,10) for j in range(1,10)}
print(li6) # Output is :{1: 9, 2: 9, 3: 9, 4: 9, 5: 9, 6: 9, 7: 9, 8: 9, 9: 9}
li7 = {
i:j for i,j in enumerate([' Wu ',' zhang '])}
print(li7) # Output is :{0: ' Wu ', 1: ' zhang '}
Be careful : There is no tuple derivation !!!
for Iterative variable in Iteratable object
A list is an iteratable object ,dir When viewing the list method, there are __iter__ Method ,
But the list is not an iterator , How to convert a list into an iterator :
li = [1,2,3,4]
it = iter(li)
Get the value of the iterator ?
for i in it:
print(i) # This will get all the values
Since it's an iterator , Just through next Method to get the value of the iterator . Do this one value at a time , Can save memory space .
next Two ways of use :
print(it.__next__()) # Output is :1
print(next(it)) # Output is :2
# -*- coding: utf-8 -*-
""" __author__ = Lonely and cold """
li = [1,2,3,4]
it = iter(li)
try:
while True:
print(next(it))
except Exception as e:
print(e)
Output is :
1
2
3
4
Question 1 : How do we implement an iteratable object ourselves ?
In a custom class , To achieve
__iter__
Magic methods
The magic method , You have to return a iterator
( You need to do it yourself )
Question two : Is there a more elegant way ?
generator !
# -*- coding: utf-8 -*-
""" __author__ = Lonely and cold """
tu = (i for i in range(1,10))
print(type(tu)) # Output is :<class 'generator'> It means this is a generator
print(dir(tu)) # You know tu There's a way __iter__ and __next__, So this is an iterator
print(tu.__next__()) # Since it is an iterator , You can use next Methods the values
Return this object
yield An object -> Pause this function
Wait for the next time next Reactivate
For example :
# -*- coding: utf-8 -*-
""" __author__ = Lonely and cold """
def fun(): # Define generator , from next Function triggers execution
print(' study hard ')
yield 1 # Return to one 1 And pause the function
print(' Day day up ')
yield 2 # Return to one 2 And pause the function
print(' Once again ')
# There is no code , trigger StopIteration abnormal
a = fun()
aa = next(a) # Output is : study hard
print(aa) # Output is : 1
bb = next(a) # Output is : Day day up
print(bb) # Output is : 2
# cc = next(a) # Output is : Once again And throw StopIteration abnormal ( You can do it yourself run Take a look ~)
# If print(type(fun())), Will be output <class 'generator'>, This function is already a generator .
Let's take another example :
# -*- coding: utf-8 -*-
""" __author__ = Lonely and cold """
def fun(ele, n):
count = 0
while True:
if count < n:
count += 1
yield ele
else:
break
a = fun('wumou', 5)
for i in a:
print(i)
generator And iterator The difference between :