How to create a generator:
For x in range (1,10000000), Sir into a list [1........9999999] if we only want the next few elements, we will find a lot of wasted space. So, if the list element can be calculated according to an algorithm, can we continue to calculate the subsequent elements in the process of the loop? This eliminates the need to create a complete list, which saves a lot of space. In Python, this side loop computes the mechanism, called the Generator (Generator).
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>
How to get the generator element, you can calculate the value of the next element by next (), until the last element is calculated, and when there are no more elements, the Stopiteration error is thrown.
for in range (1,4))print type (a)'generator'>> >> a.next ()1>>> a.next () 2>>> a.next ()3>>> A.next () Traceback (most recent ):'<stdin>'in <module>stopiteration>>>
Another way is: For loop
for in range (1,4)) for in a:print x ... 123>>>
[Python Learning Article] [Liu Xuefeng] [1] Advanced Features--Create generator Method 1 A = (x for x in range (1,3))