Python full stack development: Python iterator, generator

Source: Internet
Author: User
Tags generator

Iterator one, what is an iterator
#迭代器即迭代的工具, what is iteration? #迭代是一个重复的过程, the iteration is repeated every time, and the result of each iteration is the initial value of the next iteration while True: #只是单纯地重复, and therefore not the iteration    print (' ===> ')     l=[1,2,3]count= 0while Count < Len (l): #迭代    print (L[count])    count+=1
Second, why have iterators, what is an iterative object, what is an iterator object
#1, why do you have iterators? For sequence types: strings, lists, tuples, we can iterate over the elements that they contain by using an indexed method.
But for dictionaries, collections, files, and so on, there is no index, and if you want to take out the elements that are contained inside, you must find an iterative way that does not depend on the index, which is the iterator # #, what is an iterative object? An iterative object refers to an object with a built-in __iter__ method, namely obj.__iter__, as follows ' Hello '. __iter__ (All-in-one). __iter__[1,2,3].__iter__{' A ': 1}.__iter__{' a ', ' B '}.__iter__open (' a.txt '). __iter__#3, what is an iterator object? The result of an iterative object execution obj.__iter__ () is an iterator object, whereas an iterator object refers to an object file type that has a built-in __iter__ and built-in __next__ method is an iterator object open (' A.txt '). __iter__ () Open ( ' A.txt '). __next__ () #4, note: An iterator object must be an iterative object, and an iterator object is not necessarily an iterator object
Third, the use of iterator objects
Dic={' A ': 1, ' B ': 2, ' C ': 3}iter_dic=dic.__iter__ () #得到迭代器对象, the iterator object has __iter__ and __next__, but: iterator. __iter__ () The resulting is still the iterator itself iter_dic.__iter__ () is Iter_dic #Trueprint (iter_dic.__next__ ()) #等同于next (iter_dic) print (Iter_dic.__next __ ()) #等同于next (iter_dic) print (iter_dic.__next__ ()) #等同于next (iter_dic) # Print (iter_dic.__next__ ()) # Throws an exception stopiteration, or end flag # with an iterator, we can take a value without relying on an index iteration iter_dic=dic.__iter__ () while 1:    try:        k=next (Iter_dic)        print (Dic[k])    except stopiteration:        break        #这么写太丑陋了, we need to catch the exception, control Next,python so cool, can you help me solve it? Can, see for loop
Iv. for Loop
#基于for循环, we can completely no longer rely on the index to get the value of dic={' a ': 1, ' B ': 2, ' C ': 3}for K in dic:    print (dic[k]) #for循环的工作原理 # #: Dic.__iter__ of the object executing in () method to get an iterator object iter_dic#2: Execute Next (iter_dic), assign the resulting value to K, and then execute the Loop body Code # 2: Repeat the process until you catch the exception stopiteration, ending the loop
V. Advantages and disadvantages of iterators

Pros: 1. Provide a unified, indexed-independent iterative approach

2. Lazy calculation, only one piece of data at a time, save memory

Cons: 1. Cannot get length (only if the iteration is complete to know how many values)

2. One-time, sequential move, unable to retreat

Generator One, what is a generator

The keyword that contains yield in the function does not execute internal code when the function is called, and the resulting function return value is a generator object

Def chicken ():    print (' =====>first ')    yield 1    print (' =====>sencond ')    yield 2    print (' ===== >third ')    yield 3obj=chicken () print (obj) #<generator object func at 0x > Builder objects
Second, the generator is an iterator

The generator is essentially an iterator, which means that the generator's gameplay is actually an iterator.

Obj.__iter__obj.__next__#2, so the generator is an iterator, so you can take this value res=next (obj) print (res)
Mimic range () function
def my_range (start,stop,step=1): While    start < stop:        yield start         
For item in My_Range (1,10,2):    print (item)

# Result: 1,3,5,7,9
Iii. conclusion of yield
#1, give us a way to customize the iterator, #    can be used within the function of the yield keyword, call the function to get the result is a generator, generator is an iterator # #, yield can be used as return for the return value, the difference is that return can be returned only once the value, Yield can be returned multiple times #    because yield saves the state of the function execution

Python full stack development: Python iterator, generator

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.