python08-iterators and generators

Source: Internet
Author: User

I. What is an iterator first recap, what is recursion?

In the process of invoking a function, the function itself is called directly or indirectly.

For example, ask the road, you ask Zhang San Stove mountain where? Zhang San don't know, he said I help you to ask John Doe, John Doe to Zhang San said I don't know, you wait, I help you to ask Harry. So John Doe went to ask Harry, Harry told Li four stove mountain in XXX, John Doe on the fart to run back to tell Zhang San, Zhang San know the answer to tell you, the front is the Stove Mountain!

What is an iteration?

An iteration is a repeating process that repeats one iteration at a time, and the result of each iteration is the initial value of the next iteration

For example, your grandfather and your grandmother gave birth to your father, your father and your mother gave birth to you, and then a generation to reproduce this .... If you do not have your grandparents, you will not have your father, without your father will not have you

What is an iterator?

An object that can be called by the next () function and continually returns the next value is called an iterator, the tool of the iteration

What is an iterative object?

An object that implements an iterator protocol (how it is implemented: an __iter__ () method is defined within an object). In general, an object that can be directly applied to a for loop is called an iterative object (iterable), and a tool inside python, such as A For loop, Sum,min,max,socket, uses an iterator protocol to access an object.

x= ' Hello '
Print (dir (x))
ITER_TEST=X.__ITER__ ()

Print (iter_test)
Print (iter_test.__next__ ())
Print (iter_test.__next__ ())
Print (iter_test.__next__ ())
Print (iter_test.__next__ ())
Print (iter_test.__next__ ())
Print (iter_test.__next__ ())

What is an iterator protocol?

The object must provide a next method that either returns the next item in the iteration, or causes a Stopiteration exception to terminate the iteration (only backward cannot go forward)

Why are strings, lists, tuples, and so on an iterative object?

Because they are data types that can be traversed, that is, an element can be taken out of one.

s={1,2,3}
For I in S: #只要能被for循环遍历的对象, there are __iter__ () methods
Print (i)
ITER_S=S.__ITER__ ()
Print (iter_s)
Print (iter_s.__next__ ())
Print (iter_s.__next__ ())
Print (iter_s.__next__ ())
Print (iter_s.__next__ ())

  

What is the difference between an iterator and an iterative object?

The difference is that there are __next__ methods in the iterator, which is the most fundamental difference between them.

l=[1,2,3]
ITER_L=L.__ITER__ () #遵循迭代器协议, L is an iterative object, iter_l is an iterator
Print (iter_l.__next__ ())
Print (iter_l.__next__ ())

Why do we have a for loop?

Because the data type of the dictionary, collection, and file object is not subscript, and is unordered. If you want to take out the elements that are contained inside, you must find a way to not depend on the index, so you need a for loop.

l=[1,2,3]
Index=0
While index < Len (l): # Iterate through the elements in the list without the subscript index
Print (L[index])
Index+=1

Dic={' A ': 1, ' B ': 2} #for循环为什么遍历的是字典的key? Is all because the value returned by the next method in the Iteration protocol
ITER_D=DIC.__ITER__ ()
Print (iter_d.__next__ ())

F=open (' test.txt ', ' r+ ')
ITER_F=F.__ITER__ ()
Print (Iter_f)
Print (iter_f.__next__ (), end= ")
Print (iter_f.__next__ (), end= ")

How the For Loop works

strings, lists, tuples, dictionaries, collections, file objects These are iterative objects, and for loops when they traverse them, they first call their internal ITER method,

Turn them into an iterative object, and then call the next method of the iterator object to take the value, snapping to the stopiteration exception and terminating the iteration.

l=[1,2,3,4,5]
DIEDAI_L=L.__ITER__ ()
While True: #模拟for循环
Try
Print (diedai_l.__next__ ())
Except stopiteration:
Print (' iteration completed, loop terminated ')
Break

Advantages and disadvantages of iterators

#优点:
-Provides a unified, index-independent iterative approach
-Lazy calculation, save memory
#缺点:
-Unable to get the length (only if you know how many values are in next complete)
-Disposable, can only go back, can not forward

Second, generator what is generator?

As long as there is a yield keyword inside the function, the result of the function name () is the generator, and the function internal code is not executed. Can be understood as a type of data that automatically implements the iterator protocol, so the generator is an iterative object.

def test ():
Yield 1 #帮你返回值 and turn you into a generator
Yield 2
Yield 3
G=test ()
Print (' From function ', g) #<generator object func at 0x0000000002184360>
Print (g.__next__ ())
Print (g.__next__ ())

Expressive form Functional Type

The function contains the yield keyword, using the yield statement to return the result, instead of the Return,yield statement returning one result at a time, in the middle of each result, the state of the function is suspended so that the next time it goes away from the execution

def test ():
Yield 1 #帮你返回值 and turn you into a generator


G=test ()
Print (' From function ', g) #<generator object func at 0x0000000002184360>

An expression

First recognize the ternary expression:

Name= ' mentally handicapped '
Name= ' Little Meat '
res= ' SB ' if name = = ' mentally handicapped ' else ' handsome '
Print (res) #返回SB

The so-called ternary is if name = = ' mentally handicapped ', Else ' handsome man ', ' SB '

Come and meet the list explanation:

Egg_list=[]
For I in range (10):
Egg_list.append (' egg%s '%i)
Print (egg_list)

l=[' egg%s '%i for I in range (10)]
l1=[' egg%s '%i for I in range (Ten) if I > 5] #可以, ternary
# l1=[' egg%s '%i for I in range (Ten) if I > 5 else i] #没有四元表达式
l2=[' egg%s '%i for I in range (Ten) if I < 5]
l3=[' egg%s '%i for I in range (ten) Else ' haha '] #报错, no else

Print (L)
Print (L1)
Print (L2)

      

The last is the generator expression:

Similar to a list explanation, but the generator expression returns an object that produces results on demand instead of building a list of results at a time, saving memory compared to the list explanation

laomuji= (' egg%s '%i for I in range) #生成器表达式
Print (Laomuji)
Print (laomuji.__next__ ())
Print (laomuji.__next__ ())
Print (Next (Laomuji))
Print (Next (Laomuji))
Print (Next (Laomuji))
Print (Next (Laomuji))
Print (Next (Laomuji))
Print (Next (Laomuji))
Print (Next (Laomuji))
Print (Next (Laomuji))

yield

1. Make the function an iterator
2, compared to return, you can return multiple values, you can suspend/save the function's running state

Benefits of Generators

The use of generators produces deferred operations, which are the result of generating results when needed, rather than producing results immediately, which is the main benefit of the generator.

python08-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.