程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Lets take a look at iterators & generators in Python

編輯:Python

Catalog :

  • Each preface :
  • 1. iterator (iterator)
    • (1) List derivation : Be able to construct a new list concisely
    • (2) Upgrade Output 1-9 Even number between :
    • (2) One more level How to print out multiple values ?
    • Set derivation & The derivation of the dictionary is ready :
    • Small expansion :
    • Knowledge point supply station :
    • Small expansion :
    • 2. generator (generator)
    • (1) Tuple derivation
    • (2)yield
  • Iterator generator summary :

Each preface :

  • 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 !

1. iterator (iterator)

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 ?

  • It is a process of taking things out of the data structure in turn ~

(1) List derivation : Be able to construct a new list concisely

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]

(2) Upgrade Output 1-9 Even number between :

( 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]

(2) One more level How to print out multiple values ?

# -*- 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 & The derivation of the dictionary is ready :

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}

Small expansion :

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 !!!

Knowledge point supply station :

  • iteration :
    for Iterative variable in Iteratable object
    Each cycle will automatically make “ Iterative variable ” Point to “ The next element ”.
  • Iteratible objects are :
    Iteratable object ( Realized __iter__ This method is ): Sequence type and hash type .
  • Iterator finger :
    iterator ( Realized __iter__ and __next__ The way is , Iterator is an object ) You can only move forward, not backward .
  • Generate an iterator from an iteratable object :
    iterator = iter( Iteratable object )
    Next value = next( iterator )
    For example :

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

Small expansion :

  • for Loop implementation principle .
# -*- 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

2. generator (generator)

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 !

  • generator : The function that returns the iterator .

(1) Tuple derivation

# -*- 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 

(2)yield

  • All have yield The functions of are generators !

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)

Iterator generator summary :

generator And iterator The difference between :

  • generator , yes Python A very simple syntax is provided that allows us to write our own iterators .
    Be careful ——> generator , It's a special kind of iterator .
  • A generator is a function , The result returned is an iterator .
    An iterator is an object .

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved