#Objects with the __next__ method are considered to be iterable and can be iterated through x.__next__(). When iterating to an empty line, an error will be reported StopIteration f= open ( 'e:/kangujiao/test.txt' ) print ( iter (f) is f) #The file itself is an iterator print (f. __next__ (), end = '' ) print (f. __next__ (), end = '' ) #print(f. __next__(),end ='') #Built-in function next, it will automatically use the __next__ method of the object. Given an iterable object, calling next(x) is the same as x.__next__(), and an error will be reported when iterating to an empty line StopIteration f= open ( 'e:/kangyuujiao/test.txt' ) print ( next (f), end = '' ) print ( next (f), end = '' ) #print(next(f), end='') #When the for loop starts, it will be passed to the iter built-in function, In order to get an iterator from an iterable object, the returned object contains the required next method l=[ 1 , 2 , 3 ] print ( iter (l) is l) #list is not an iterator i= iter (l) print ( i. __next__ ()) print (i. __next__ ()) print (i. __next__ ())
#Other iteration environments print ( sum ([ 1 , 2 , 3 , 4 , 5 ])) #15 print ( list ( open ( 'e:/kangujiao/test.txt' ))) #returns the lines in the file consisting of List print ( tuple ( open ( 'e:/kangyujiao/test.txt' ))) #return a tuple of lines in the file print ( '&&' .join( open ( 'e:/kangyujiao/test.txt' ))) #returns a string of lines in the file a,b,c,d= open ('e:/kangyuujiao/test.txt' ) #The lines in the file are assigned to a,b,c,d print (a,b,c,d) a,*b= open ( 'e:/kangyujiao/test.txt' ) #The first line in the file is assigned to a, and the others are assigned to b print (a,b) print ( set ( open ( 'e:/kangyujiao /test.txt ' ) )) #return the set of lines in the file print ({i:j for i,j in enumerate ( open ( 'e:/kangyujiao/test.txt' ))}) #return to the file A dictionary of lines
#Multiple iterators vs a single iterator# range itself is not an iterator. After an iterator is generated, it supports multiple iterators, and these iterators will remember their respective positions r= range ( 3 ) i1= iter (r) print ( next (i1)) #0 print ( next (i1)) #1 i2= iter (r) print ( next (i2)) #0 print ( next (i2)) #1 #zip , map and filter do not support multiple active iterators on the same result z= zip (( 1 , 2 , 3 ),( 4 , 5 , 6 )) i1=iter(z) i2=iter(z) print(next(i1)) #(1,4) print(next(i1)) #(2,5) print(next(i1)) #(3,6) z=map(abs, (-1,-2,-3,-4)) i1=iter(z) i2=iter(z) print(next(i1)) #1 print(next(i1)) #2 print(next(i1)) #3