1. List-Generated
>>> [i**2 for I in range (10)][0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
This process takes elements from the range (10) list, calculates the square of the element, and then puts it in the other list
2. The code in "1" can be written in this form
>>> def f (x): return x**2 for in range[ 014964 Bayi]
3. The number of elements in a tuple (list) is n, and a tuple (list) assigns values to n variables
>>> a= >>> x,y,z=a>>> x1>>> y2> >> Z3
>>> b=[1,2,3]>>> x1,y1,z1=b>>> x11>>> y12 >>> Z13
4. Generators are created in two ways
Method One:
>>> (i**2 for I in range) <generator object <genexpr> at 0x03b21480>
Generator is the generator.
Here we generate a generator object, why do we generate such an object instead of a list? Because the list is putting values in the list ... When there is a lot of data, memory is consumed very much.
Nothing exists in the generator object ... But it can get everything. Saves space with the generator.
The values in the generator can only be taken one
>>> g= (i**2 forIinchRange (10))>>>Next (g) 0>>>Next (g)1>>>Next (g)4>>>Next (g)9>>>Next (g)16>>>Next (g)25>>>Next (g)36>>>Next (g)49>>>Next (g)64>>>Next (g)81>>> Next (g)#Out of boundsTraceback (most recent): File"<pyshell#34>", Line 1,inch<module>Next (g) Stopiteration
The generator is an iterative object, so the code above can be abbreviated as:
for in range (+)) for in S: # internal: The For In loop automatically calls next, gets a value, uses I to take this value, after use , this value is removed by the garbage collection mechanism ... So it saves space . Print(i) 0149162536496481
Method Two:
Use the keyword yield
The essence of the generator is a function with the yield keyword
def A (): Print ("ok1") yield 1 #yield返回一个值 print("ok2") yield 2 >>> Next (A ()) #a () is a generator, and each time next () runs until a value is returned OK11> >> Next (A ()) Ok11
And, of course, the following wording:
for inch A (): #i每次存一个yield返回的值 print(i) ok11ok22
5: What is an iterative object? An iterative object can use the for
An object that has a ITER method inside is an iterative object
Iterative objects are: list, tuple, string, dictionary, builder object
<python Full Stack Development Basics > Learning Process Note "17d" generator