列表生成器
简单的列表生成:
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
带循环的列表生成:
>>> [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']
for 循环引入变量,如 items
:
>>> d = {'x': 'A', 'y': 'B', 'z': 'C' }
>>> [k + '=' + v for k, v in d.items()]
['y=B', 'x=A', 'z=C']
>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']
练习
如果list中既包含字符串,又包含整数,由于非字符串类型没有lower()方法,所以列表生成式会报错,请修改列表生成式,通过添加if语句保证列表生成式能正确地执行:
>>> L = ['Hello', 'World', 18, 'Apple', None]
>>> [s.lower() for s in L]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <listcomp>
AttributeError: 'int' object has no attribute 'lower'
修改:
# -*- coding: utf-8 -*-
L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = [s.lower() for s in L1 if isinstance(s,str)]
# 测试:
print(L2)
if L2 == ['hello', 'world', 'apple']:
print('测试通过!')
else:
print('测试失败!')
小结
运用列表生成式,可以通过一个list推导出另一个list,从而快速生成list。
生成器
练习
杨辉三角定义如下:
1
/ \
1 1
/ \ / \
1 2 1
/ \ / \ / \
1 3 3 1
/ \ / \ / \ / \
1 4 6 4 1
/ \ / \ / \ / \ / \
1 5 10 10 5 1
把每一行看做一个list,试写一个generator,不断输出下一行的list:
# -*- coding: utf-8 -*-
def triangles():
L = [1]
while True:
yield L
# 列表间的加号用法见下面‘注’
L=[L[0]]+[L[i]+L[i+1] for i in range(len(L)-1)]+[L[0]]
def triangles(m):
L = [1]
n = 0
while n < m:
yield L
L=[L[0]]+[L[i]+L[i+1] for i in range(len(L)-1)]+[L[0]]
n = n + 1
for x in triangles(10):
print(x)
注:
对于列表来说,
>>> [1] + [2]
>>> [1, 2]