First, why use the generator:
With list generation, we can create 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.
Second, the method of using generators:
There are a number of ways to create a generator. The first method is simple, as long as a list of the generated formula is []
changed ()
to create a generator:
for in range () >>> 1, 4, 9, +, (+), +, +, Bayi]for in Range (Ten)>>> g<generator object <genexpr> at 0x104feab40>
Of course, this method of constant invocation is next()
too perverted, the correct way is to use for
loops, because generator is also an iterative object:
for in range (ten)) for in G: ... Print N. ... 0149162536496481
So, after we create a generator, we basically never call next()
the method, but iterate through the for
loop.
Generator is very powerful. If the calculated algorithm is more complex, and the loop with similar list generation for
cannot be implemented, it can also be implemented with functions.
for in fib (6): ... Print n . ... 112358
Python Builder (Generator)