List attributes: lists are generated once
A = [1,2,3,4,5,6,7,8,9]
Or
[i*2 for I in range] # # #---> list generation
===[2,4,6,8,10,12,14,16,18,20]===
Two List of differences:
1 list is written dead, 2 list can do some operations inside to output the corresponding things
The purpose of the list generation is to make the code more concise and to implement more complex functions, such as passing the value of I into a function
[fun (i) for I in range (10)]
Build: A list can be created directly from a build, but limited by the size of the memory, the capacity of the list is finite, and the creation of a list of large amounts of data, not only occupies a large amount of memory, and if you only access the previous elements, then the space occupied by the subsequent elements is Wasted.
so, If the list can be inferred from an algorithm, we can infer the subsequent required list elements in the loop process without having to create a complete list, thus greatly saving memory Space. In python, the way the side loops the next list element is called the generator: generator
There are many ways to create a generator, and the first simple method is to modify the [] list generation to () to create a generator
[i*2 for I in range] # # #---> list generation
= = Result ===[2,4,6,8,10,12,14,16,18,20]===
(i*2 for I in Range) # # #--->generator
= = Result ===<generator Object <genexpr> at 0x1022ef630>===
Generator is one element per call, and no subsequent elements are generated if not called, saving memory space
Cases:
g = (i*2 for I in range (10))
Print (g.__next__ ())
Print (g.__next__ ())
Print (' ******** ')
Print (g.__next__ ())
= = Result = = =
0
2
********
4
It only __next__ () method, no other method, it can not be sliced, such as want to take the 3rd value of G (2) is not possible
The above method can also be used to call it in a circular way
In the case of the Fibonacci sequence, except for the first number, any number is added by the preceding two numbers:
1,1,2,3,5,8,13,21,34 .....
The Fibonacci sequence is not written in list generation, but it is easy to use a function:
def fib (max):
n,a,b=0,0,1
While N < max:
Print (b)
a,b= b,a+b
n = n+1
Return ' Done '
Python list-generated