List-generated: [Exp for Iter_var in iterable]
There will also be dictionary-generated, set-generated, no tuple-generated, the syntax of the tuple-generated formula is occupied
Dictionary generation, collection generation, that is, the outside of the parentheses into the {} Dictionary is a key-value pair, the collection can be distinguished from it
Generator: There are two ways to do this:
One is to write a generative formula into (), which is a generator,
1 #Replace [] in List-generation with ()2GE = (x forXinchRange (1,6))3 Print(Ge,type (GE))4 5 #The generator needs to get the data through the next () method, and once the call returns a data6 Print(Next (GE))7 Print(Next (GE))8 Print(Next (GE))9 Print(Next (GE))Ten Print(Next (GE))
View Code
yiled-expression
The yield statement returns one result at a time, in the middle of each result, suspends the state of the function so that the next time it leaves the
1 #generated by function and yield keyword2 #a function that uses yield is called a generator (generator)3 #The yield statement returns one result at a time, in the middle of each result, suspends the state of the function so that the next time it leaves the execution4 defTest (n):5 forIinchRange (1,n + 1):6 yieldI7 #print (i)8 #Get Generator9result = Test (10)Ten Print(Result) One A #the generator can traverse only once, so there will be no output below - forXinchResult: - Print(x) the
View Code
Iterative objects: Can be used in the structure of the all are iterative objects, commonly used are list, set, tuple, dict, str, generator
Determine if it is an iterator that can be judged with isinstance (, iterable) and need to be imported iterable
1 #introducing from collection import Iterable2 fromCollectionsImportiterable3 Print(Isinstance ("", iterable))#True4 Print(Isinstance ({},iterable))#True5 Print(Isinstance ((), iterable))#True6 Print(Isinstance (1,iterable))#False
View Code
Iterators: Those generators are iterators, and iterators are iterative objects, but iterative objects are not necessarily iterators
The method of judging is also using the same function parameter to replace iterator need to import iterator, iterable
1 fromCollectionsImportiterator,iterable2 Print(Isinstance ([],iterator))#False3 Print(Isinstance ((), Iterator))#False4 Print(Isinstance ({},iterator))#False5 Print(Isinstance ("", Iterator))#False6 Print(Isinstance (x forXinchRange (0,6)), Iterator))#True The generator is an iterator7 Print(Isinstance (x forXinchRange (0,6)), iterable))#True The generator is also an iterative object
iterators
Iterators can be converted to and from an iterative object
1 Print(Isinstance (ITER ([]), Iterator))#True2 Print(Isinstance (ITER (()), Iterator))#True3 Print(Isinstance (ITER ({}), Iterator))#True4 Print(Isinstance (ITER (""), Iterator))#True5 6L2 = iter (L1)#convert a list to an iterator7 Print(Next (L2))#use next to get the elements in the iterator
View Code
27 Basics of Python programming