Python notes • 12th-function (iv) iterators and generators

Source: Internet
Author: User

An iterator

The concept of an iteration

#迭代器即迭代的工具, 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 do we have iterators? What is an iterative object? What is an iterator object?

1 #1. Why do I have iterators? 2 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 iterator3 4 #2. What is an iterative object? 5An iterative object refers to an object that has a built-in __iter__ method, that is, obj.__iter__, as follows6 'Hello'.__iter__7(a).__iter__8[A.]__iter__9{'a': 1}.__iter__Ten{'a','b'}.__iter__ OneOpen'a.txt').__iter__ A  - #3. What is an iterator object?  -You can iterate over an object to execute obj.__iter__() The result is an iterator object the An iterator object is an object that has a built-in __iter__ and a built-in __next__ method. -  - file type is an iterator object -Open'a.txt').__iter__() +Open'a.txt').__next__() -  +  A #4. Note: atAn iterator object must be an iterative object, and an iterative object is not necessarily an iterator object

Use of three-iterator objects

1dic={'a': 1,'b': 2,'C': 3}2Iter_dic=dic.__iter__()#gets the iterator object, which is __iter__ and __next__, but the iterator. __iter__ () still gets the iterator itself3Iter_dic.__iter__() isIter_dic#True4 5 Print(Iter_dic.__next__())#equivalent to Next (iter_dic)6 Print(Iter_dic.__next__())#equivalent to Next (iter_dic)7 Print(Iter_dic.__next__())#equivalent to Next (iter_dic)8 #print (iter_dic.__next__ ()) #抛出异常StopIteration, or End flag9 Ten #with iterators, we can take values without relying on index iterations. OneIter_dic=dic.__iter__() A  while1: -     Try: -k=Next (iter_dic) the         Print(Dic[k]) -     exceptstopiteration: -          Break -          + #This is too ugly to write, we need to catch the exception, control Next,python so good, can you help me solve it? Can, see for loop

Four 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

Advantages and disadvantages of five iterators

#优点:  -Provides a unified, index-independent iterative approach  -lazy computing, saving memory # Disadvantages:  -Unable to get the length (only after the next finish to know how many values)-one  -time, can only go backwards, not forward
Two generators

What is a generator

#只要函数内部包含有yield关键字, the result of the function name () is the generator and does not execute the function internal code def func ():    print (' ====>first ')    yield 1    print (' = ===>second ')    yield 2    print (' ====>third ')    yield 3    print (' ====>end ') G=func () print (g) #< Generator object Func at 0x0000000002184360>

The second generator is an iterator

G.__iter__g.__next__#2, so the generator is an iterator, so you can take this value res=next (g) print (res)

Python notes • 12th-function (iv) iterators and generators

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.