16. The road of python precipitation--iterator

1. Iterator

1. What is the iterator protocol: the object must provide a next method, and the execution of this method must return the next item in the iteration, or cause a StopIteration exception to terminate the iteration (can only go backward, not forward).

2. Iterable object: an object that implements the iteration protocol (how to implement: an __iter__() method is defined inside the object).

3. The protocol is a convention. Iterable objects implement the iterator protocol. Python's internal tools (such as for loops, sum, min, max functions, etc.) use the iterator protocol to access objects.

4. Python's powerful for loop mechanism:

       The essence of the for loop: loop all objects, all using the iterator protocol.

       Original source:
Many people think that the essence of the for loop is to follow the iterator protocol to access objects, so the objects of the for loop must be iterators, yes, in this case, the for loop can traverse (string, list , tuples, dictionaries, sets, file objects), then these types of data must be iterable objects? But why define a list li = [1,2,3,4,5] without a next() method.

(Strings, lists, tuples, dictionaries, sets, file objects) These are not iterable objects, but in the for loop, their internal __iter__() method is called to turn them into iterable objects. Then the for loop calls the __next__() method of the iteration object to get the value, and the for loop catches the StopIteration exception to terminate the iteration.

5. For loop access method:
The essence of the for loop is to follow the access method of the iterator protocol. First call the iter_li = li.__iter__() method, or directly iter_li=iter(li), and then execute iter_li.next() in turn, until The for loop catches the stopiteration to terminate the loop. The essence of all objects in the for loop is the same principle.
6, paving

1 x = 'hello'
2 # print(dir(x))
3 iter_test = x.__iter__()        
4 print(iter_test)
5 print(iter_test.__next__())
6 print(iter_test.__next__())
7 print(iter_test.__next__())
8 print(iter_test.__next__())
9 print(iter_test.__next__())
 
1 li = [1,2,3,4 ]
 2 iter_li = li. __iter__ () #Following the iterable protocol, so an iterable object is generated 
3  print (iter_li. __next__ ())
 4  print (iter_li. __next__ ())
 

7, l is applied to list, and the comparison of for loop and while loop

1 li = [1,2,3,4 ]
 2  for i in li:   #Because li has the __iter__() attribute, it has the __next__() attribute, which can be iterated 
3      print (i)           # for loop Universal applicability 
4  
5 index = 0
 6  while index < len(li): #This     method is only applicable to lists, strings, elements, these types with iterable attributes, beyond these, this method cannot be used 
7      print ( li [index])
 8      index+=1
1 1
2 2
3 3
4 4
5 1
6 2
7 3
8 4

8. For set applications

1 se = {1,2,3,4,5,6}
2 for i in se:
3     print(i)
4 se_iter = se.__iter__()
5 print(se_iter.__next__())
6 print(se_iter.__next__())
7 print(se_iter.__next__())
1 1
2 2
3 3
4 4
5 5
6 6
7 1
8 2
9 3

9. For dict application

1 in = { ' a ' :1, ' b ' :2, ' c ' :3, ' d ' :4 }
 2 iter_di = di. __iter__ ()
 3  print (iter_di. __next__ ( ))
 4  print (iter_di. __next__ ( ))
 5  print (iter_di. __next__ ( ))
1  a
 2  b
 3 c

10. Open files with iteration

1 f = open('test.txt','r+',encoding='utf-8')
2 iter_f = f.__iter__()
3 print(iter_f)
4 print(iter_f.__next__(),end='')
5 print(iter_f.__next__(),end='')
6 print(iter_f.__next__(),end='
1 <_io.TextIOWrapper name='test.txt' mode='r+' encoding='utf-8'>
2 12344556
3 abcdef
4 ABCDEFG

11. Exception operations: try and except

1 li = [1,2,3,4,5 ]
 2 diedai_li = li.__iter__ ( )
 3  
4  while True:
 5      try :
 6          print (diedai_li.__ next__ ())
 7      except StopIteration:
 8          print ( ' Iteration completed, loop terminated ' )
 9          break
1 1
 2 2
 3 3
 4 4
 5 5
 6 iteration completed, loop terminated

12. The iterator direction: (can only go backward, not forward).

1 ll = [ ' grandfather ' , ' dad ' , ' son ' , ' grandson ' , ' great grandson ' ]
 2 iter_ll = iter(ll)             # ll.__iter__() is equivalent to iter(ll) 3 print (iter_ll. __next__ ())
 4 print (next(iter_ll))
 5 print (iter_ll. __next__ ())
 6 print (next(iter_ll))
    
1  grandpa
 2  dad
 3  son
 4 grandson

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325149504&siteId=291194637