I. List-generated
List generation is the Python setting that can be used to generate lists .
To generate a 0-9 list we can implement the following code:
>>> list (range1, 2, 3, 4, 5, 6, 7, 8, 9)
But what if the resulting list is more complex? For example, the build contains 02, 12, 22 ... 92 such a list;
>>> L = [] for in range: ... L.append (i*i) ... >>>1, 4, 9, 16, 25, 36, 49, 64, 81]
In the above code, we use the For loop to append values into the list L, although can be achieved, but also low burst ~ ~ ~, the following through a line of code!!!
for in range (1, 4, 9, 16, 25, 36, 49, 64, 81]
In addition, list generation can generate more complex lists. list generation allows you to quickly generate a formatted list.
>>> D ={"name":"Nadech"," Age":" A","Address":"Nanjing"}>>> [key+"="+value forKey,valueinchD.items ()] ['Name=nadech','age=22','address=nanjing']
Second, generator
With a list-generated formula, we can create all the elements of a list directly.
However, with memory limitations, the list capacity is certainly limited. Also, creating a list of 1 million elements takes up a lot of storage space, and if we just need to access the first few elements, the vast majority of the space behind it is wasted.
If the list can be calculated as needed, one side of the loop can solve the above problem. This mechanism is called the Generator (generator).
There are two types of generators, the first of which is to change the [] in the list generation to (), and the second is to include yield
for in range (1,3))>>> Next ( g)1>>> Next (g)4>>> Next ( g) Traceback (most recent): '<stdin>' in <module >stopiteration
>>> (I*i for I in range (10))
<generator Object <genexpr> at 0x0000029ea41490f8>
>>> for I in G:
... print (i)
...
1
4
The bold part of the above code shows that the creation generator returns the address of a generator object, not a list of all the elements that directly contain it.
By invoking next, you can generate the value of the next element, but in practice we do not call next more than once, but instead get the generator's elements through a for loop.
The second thing we're going to introduce is the yield,
Python note 10 (list generation, generator)