python generator generator

What is a generator? According to a fixed algorithm and initial conditions, elements are generated while looping without having to store the list in advance.

Why use generators? Save memory.

refer to:

http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014317799226173f45ce40636141b6abc8424e12b5fb27000

The method of generating the generator:

1. Change the [] of a list comprehension to () to create a generator

>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x7f9ab711c0a0>
>>> type(g)
<type 'generator'>  #类型是generator
>>> type(L)
<type 'list'>

2. In the custom function, change print to yield, and use for loop to output the result

>>> def sanjiao(max):
...     n=0
...     b=[1]
...     a=[1,1]
...     while n <max:
...             yield b
...             if (len(b)==1):
...                     b=a
...             else:
...                     for i in range(len(b)-1):
...                             a.insert(i+1,b[i]+b[i+1])
...                     b=a
...             a=[1,1]
...             n=n+1
... 
>>> sanjiao(10)
<generator object sanjiao at 0x7f9ab7160d20>
>>> for i in sanjiao(10):
...     print i
... 
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
[1, 5, 10, 10, 5, 1]
[1, 6, 15, 20, 15, 6, 1]
[1, 7, 21, 35, 35, 21, 7, 1]
[1, 8, 28, 56, 70, 56, 28, 8, 1]
[1, 9, 36, 84, 126, 126, 84, 36, 9, 1]

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325914881&siteId=291194637