Python (eight)

Source: Internet
Author: User

What is an iterator protocol

1. An iterator protocol means that an 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)

2. An iterative object: An object that implements an iterator protocol (how to: Define an __iter__ () method within an object)

3. The Protocol is a convention that iterates over an object, implements an iterator protocol, and Python's internal tools (such as a For loop, Sum,min,max function, etc.) use an iterator protocol to access an object.

two powerful for loop mechanism in Python

The nature of the For loop: Loop through all objects, all using an iterator protocol.

Radical reform

Many people will think that the nature of the For loop is to follow the iterator protocol to access the object, then the For loop object must be an iterator ah, yes, so that the For loop can traverse (strings, lists, tuples, dictionaries, collections, file objects), then these types of data must be an iterative object ah? But why the fuck do I define a list l=[1,2,3,4] without L.next () method, to punch a face?

(strings, lists, tuples, dictionaries, collections, file objects) These are not iterative objects, but in the for loop, they call their internal __iter__ methods and turn them into an iterative object.

The For loop then calls the __next__ method of the iteration object to fetch the value, and the for loop catches the stopiteration exception to terminate the iteration

1 l=[' A ', ' B ', ' C '] 2 #一: Subscript access mode 3 print (L[0]) 4 print (l[1]) 5 print (l[2]) 6 # print (l[3]) #超出边界报错: Indexerror 7  8 #二: Follow iterators Protocol access Mode 9 diedai_l=l.__iter__ () print (diedai_l.__next__ ()) print (diedai_l.__next__ ()) Print (diedai_l.__next__ ( ) # Print (diedai_l.__next__ ()) #超出边界报错: StopIteration14 #三: For loop access #for循环l本质就是遵循迭代器协议的访问方式, call diedai_l=l.__ first Iter__ () method, or direct Diedai_l=iter (l), then execute Diedai_l.next () sequentially until the for loop snaps to the stopiteration termination loop
#for循环所有对象的本质都是一样的原理
+ For I in L: #diedai_l =l.__iter__ () print (i) #i =diedai_l.next () #四: Use while to simulate what the for loop does diedai_l=l.__ iter__ () true:24 try:25 print (diedai_l.__next__ ()) except stopiteration:27 print (' Iteration complete , cycle terminated ')
three reasons for a for loop

Based on the above list of three kinds of access, smart you immediately see the clues, so you naively loudly shouted, you do not tease me to play it, with the subscript of access, I can traverse a list like this AH

L=[1,2,3]index=0while Index < Len (l):    print (L[index])    index+=1# to yarn for loop, to yarn for loop, to yarn for loop

Yes, sequence type strings, lists, tuples have subscripts, you access them in the above way, perfect! But have you ever thought about the feeling of a non-sequential type like a dictionary, a collection, a file object, so, young man, the For loop is based on an iterator protocol that provides a uniform way to traverse all objects, that is, before the traversal, the __iter__ method of the object is called to convert it to an iterator. Then use the iterator protocol to implement circular access, so that all objects can be traversed by the For loop, and you see the effect is true, this is omnipotent for loop, enlightenment!

Python (eight)

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.