# 【2.1.2】列表生成器--yield

class A(object):
x = 1
gen = (x for _ in xrange(10))  # gen=(x for _ in range(10))
if __name__ == "__main__":
print(list(A.gen))

## 一、列表生成式

>>> range(1, 11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

>>> L = []
>>> for x in range(1, 11):
...    L.append(x * x)
...
>>> L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

>>> [x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

for循环后面还可以加上if判断，这样我们就可以筛选出仅偶数的平方：

>>> [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]

>>> [m + n for m in 'ABC' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

>>> import os # 导入os模块，模块的概念后面讲到
>>> [d for d in os.listdir('.')] # os.listdir可以列出文件和目录
['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']

>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.iteritems()]
['y=B', 'x=A', 'z=C']

>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']

L = ['Hello','World',18,'Apple',None]
k = [x.lower() for x in L if isinstance(x,str)]
print k

isinstance(x, str)

## 二、生成器

### 方法一：把一个列表生成式的[]改成()

>>> 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
at 0x104feab40>

>>> g.next()
0
>>> g.next()
1
>>> g.next()
4
>>> g.next()
9
...
>>> g.next()
Traceback (most recent call last):
File "", line 1, in
StopIteration

>>> g = (x * x for x in range(10))
>>> for n in g:
...     print n
...
0
1
4

### 方法二：yield

def fib(max):
n, a, b = 0, 0, 1
while n < max:
print b
a, b = b, a + b
n = n + 1

>>> fib(6)
1
1
2
3
5
8

def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1

>>> fib(6)

>>> def odd():
...     print 'step 1'
...     yield 1
...     print 'step 2'
...     yield 3
...     print 'step 3'
...     yield 5
...
>>> o = odd()
>>> o.next()
step 1
1
>>> o.next()
step 2
3
>>> o.next()
step 3
5
>>> o.next()
Traceback (most recent call last):
File "", line 1, in
StopIteration

>>> for n in fib(6):
...     print n
...
1
1
2
3
5
8

## 三、变量作用域

class A(object):
x = 1
gen = (lambda x: (x for _ in xrange(10)))(
x)  # gen=(x for _ in range(10))
if __name__ == "__main__":
print(list(A.gen))

class A(object):
x = 1
gen = (A.x for _ in xrange(10))  # gen=(x for _ in range(10))
if __name__ == "__main__":
print(list(A.gen))