Iterators and generators

Source: Internet
Author: User

Iterators

The concept of iterators

#迭代器即迭代的工具, 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

Why do we 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

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

Using the For Loop loop iterator object

#基于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 iterators

#优点:  -Provides a unified, index-independent iterative approach  -lazy computing, saving memory # Disadvantages:  -Unable to get length (only after next is finished to know how many values)  -one-time, can only go backwards, not forward, that is, Each cycle will cycle through the elements of the object at once.
Generator

Builder Concepts

#只要函数内部包含有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 generator is a special iterator

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

In contrast to iterators, the benefit of the generator is that it does not generate all the recycled elements at once, but instead takes one element at a time, thus reducing the use of memory and cups.

Iterators and generators

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.