python核心编程
第8章
8.12 列表解析
[expr for iter-var in iterable]
>>> [x**2 for x in range(6)]
[0, 1, 4, 9, 16, 25]
>>>
扩展
[expr for iter-var in iterable if cond-expr]
>>> [x for x in seq if x%2]
[1, 3, 5, 9, 11, 33, 45]
>>>
矩阵例子,迭代一个3行5列的矩阵
>>> [(x+1,y+1) for x in range(3) for y in range(5)]
[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5), (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5)]
>>>
检查文件中字符数
>>> f = open('LICENSE.txt','r')
>>> len([word for line in f for word in line.split() ])
4644
>>> len([word for line in f for word in line.split()])
0
>>> f = open('LICENSE.txt','r')
>>> len([word for line in f for word in line.split()])
4643
>>>
f.seek(0)# 返回文件头
8.13生成器表达式(列表解析的扩展)
列表解析:
[expr for iter-var in iterable if cond-expr]
生成器
(expr for iter-var in iterable if cond-expr)
区别:列表在循环后会创建一个比较大的列表。
>>> rows = [1,2,3,17]
>>> def cols():
yield 56
yield 2
yield 1
>>> x_product_pairs = ((i,j) for i in rows for j in cols())
>>> for pair in x_product_pairs:
print(pair)
(1, 56)
(1, 2)
(1, 1)
(2, 56)
(2, 2)
(2, 1)
(3, 56)
(3, 2)
(3, 1)
(17, 56)
(17, 2)
(17, 1)
>>>
这里面的yield好像是关键字。这里把cols()函数可以当做列表处理。