# python中的列表生成式与生成器学习教程

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

>>> [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
>>> [d for d in os.listdir(‘.’)]
[‘readme.md’, ‘.git’, ‘image’, ‘os’, ‘lib’, ‘sublime-imfix’, ‘src’]

>>> 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’, ‘ibm’, ‘apple’, 12, 34]
>>> [s.lower() if isinstance(s,str) else s for s in l]
[‘hello’, ‘world’, ‘ibm’, ‘apple’, 12, 34]

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
list(range(1, 11))
# 生成1乘1，2乘2…10乘10
l = []
for x in range(1, 11):
l.append(x * x)
# 上面太麻烦，看下面
[x * x for x in range(1, 11)]
# [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# 加上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
[d for d in os.listdir(‘.’)] # on.listdir可以列出文件和目录
# 列表生成式也可以使用两个变量来生成list:
d = {‘x’: ‘a’, ‘y’: ‘b’, ‘z’: ‘c’}
[k + ‘=’ + v for k, v in d.items()]
# [‘x=a’, ‘z=c’, ‘y=b’]
# 把一个list中所有的字符串变成小写
l = [‘hello’, ‘world’, ‘ibm’, ‘apple’]
[s.lower() for s in l]
# [‘hello’, ‘world’, ‘ibm’, ‘apple’]
l1 = [‘hello’, ‘world’, 18, ‘apple’, none]
l2 = [s.lower() for s in l1 if isinstance(s, str)]
print(l2)
# [‘hello’, ‘world’, ‘apple’]
# isinstance函数可以判断一个变量是不是字符串

>>> g = (x * x for x in range(10))
>>> g

>>> g.next()
0
>>> g.next()
1
>>> g.next()
4
>>> g.next()
9
>>> g.next()
16
>>> g.next()
25
>>> g.next()
36
>>> g.next()
49
>>> g.next()
64
>>> g.next()
81
>>> 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

1, 1, 2, 3, 5, 8, 13, 21, 34, …

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

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

>>> fib(6)

>>> fib(6).next()
1

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

def odd():
print ‘step 1’
yield 1
print ‘step 2’
yield 2
print ‘step 3’
yield 3
if __name__ == ‘__main__’:
o = odd()
while true:
try:
print o.next()
except:
break

Posted in 未分类