1.列表推导式
#coding=utf-8\
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
tshirts = [(color, size) for color in colors for size in sizes]
print(tshirts)
当列表推导式中有多个for时,按如下顺序生成列表:
[('black', 'S'), ('black', 'M'), ('black', 'L'), ('white', 'S'), ('white', 'M'), ('white', 'L')]
生成器表达式和列表推导的语法相似,只不过把方括号换成圆括号。
#coding=utf-8\
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
tshirts = ((color, size) for color in colors for size in sizes)
print(tshirts)
此时的输出不是一个列表,不是一个元组,而是一个可迭代的生成器对象,所以可以节省内存:
输出:
<generator object <genexpr> at 0x0000014950967360>
#coding=utf-8\
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
tshirts = tuple((color, size) for color in colors for size in sizes)
print(tshirts)
结果:
(('black', 'S'), ('black', 'M'), ('black', 'L'), ('white', 'S'), ('white', 'M'), ('white', 'L'))
生成器表达式从来不会开辟一块内存来存储列表或元组,从而可以节省内存开销:
#coding=utf-8\
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
for tshirt in ('%s %s'%(c, s) for c in colors for s in sizes):
print(tshirt)
输出:
black S
black M
black L
white S
white M
white L