An object that can iterate is called an iterative object, and an iterator and a generator function are iterative objects.
List Resolution Expressions: You can easily and efficiently process an iterative object and generate a list of results
Example code:
for in range ()# output [0,1,4,9,16,25,36,49,64,81]
Builder expression: A generator can be returned quickly and easily. The syntax and list parsing of the builder expression is basically the same, except that [] is replaced by ()
The generator's data is generated only when it is called
Example code:
for in range ()print(a)# output, print the Generator object address <generator Object <genexpr> at 0x000001a4118978e0>
Call Method 1:
Print# equivalent to print (a.__next__ ())
Call Method 2:
For I in A: print (i)
Call Method 3:
while True: Try : Print (Next (a)) except stopiteration: Break
Generator functions
Example code:
deffib (): A, B= 0,1 whiletrue:a,b= b,a+byieldbPrint(FIB ()) forFinchfib ():ifF < 1000: Print(f)Else: Break#Output Results<generator Object fib at 0x0000024f66a478e0>123581321345589144233377610987
Iterative and Iterative objects:
1, can iterate object: iterable
Series objects are iterative objects, and generator functions and generator expressions are also iterative objects.
Determine if an iterative object is being tested through the methods in the collections module, for example:
Import for in range (123print(isinstance (a,collections). iterable))print(isinstance (b,collections. iterable))# output result TrueFalse
2, Iterators: Iterator
You can use the built-in function next (), call the iterator's __next__ () method, and then return to the next item value object is the iterator
Import= [1,2,3,4]print(isinstance (b,collections. iterable))print(isinstance (b,collections. Iterator)# output result, B is an iterative object, but not an iterator truefalse
Like lists, dictionaries, tuples are iterative objects, but not iterators, we can use the built-in function iter () to convert to an iterator, the sample code:
Import= [1,2,3,4]print(isinstance (b,collections. iterable))print(isinstance (b,collections. Iterator))print(Isinstance (ITER (b), collections. Iterator))# output result truefalsetrue
Cond...
1.17 Python Basics-iterators and generators first knowledge