[ Web Proxy ]
URL:
Viewing: https://raw.githubusercontent.com/magic-coder/Python/master/python7/4.md [Back]  [Original]

#  #

## 1 ##

 1000 

 list Python generator

 Python  yield generator



 yield yield next()




## 2 ##

 `[]`  `()`

```python
# -*- coding: UTF-8 -*-
gen= (x * x for x in range(10))
print(gen)
```



```txt

```

 List  generator  `[]`  `()`   ( yield )   ( lazy evaluation call by need ) evaluated 




## 3 ##

 for 

```python
# -*- coding: UTF-8 -*-
gen= (x * x for x in range(10))

for num  in  gen :
	print(num)
```

 next() 


## 4 ##

 `[]`  `()`

for



```python
# -*- coding: UTF-8 -*-
def my_function():
    for i in range(10):
        print ( i )

my_function()
```



```txt
0
1
2
3
4
5
6
7
8
9
```

 `print ( i )`  `yield i` 

```python
# -*- coding: UTF-8 -*-
def my_function():
    for i in range(10):
        yield i

print(my_function())
```



```txt

```





```python
# -*- coding: UTF-8 -*-
def fibon(n):
    a = b = 1
    for i in range(n):
        yield a
        a, b = b, a + b

# 
for x in fibon(1000000):
    print(x , end = ' ')
```



![](http://upload-images.jianshu.io/upload_images/2136918-304e50af22b787ce?imageMogr2/auto-orient/strip)

 generator  return  generator  next()  yield yield 



```python
# -*- coding: UTF-8 -*-
def odd():
    print ( 'step 1' )
    yield ( 1 )
    print ( 'step 2' )
    yield ( 3 )
    print ( 'step 3' )
    yield ( 5 )

o = odd()
print( next( o ) )
print( next( o ) )
print( next( o ) )
```



```txt
step 1
1
step 2
3
step 3
5
```

odd  generator yield  3  yield  yield  `print( next( o ) ) ` , generator 

## 5 ##



```python
# -*- coding: UTF-8 -*-
def triangles( n ):         # 
    L = [1]
    while True:
        yield L
        L.append(0)
        L = [ L [ i -1 ] + L [ i ] for i in range (len(L))]

n= 0
for t in triangles( 10 ):   # 
    print(t)
    n = n + 1
    if n == 10:
        break
```



```txt
[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]
```

Web Proxy Viewer  |  New URL  |  Original Page