colors = ['black', 'white']
sizes = ['S', 'M', 'L']
# 写法1
tshirts = [(color, size) for color in colors
for size in sizes]
# 写法2
tshirts = [(color, size) for size in sizes
for color in colors]
这里得到的结果是先颜色后尺码。所以结果取决于列表生成式中()中属性的顺序。
colors = ['black', 'white']
sizes = ['S', 'M', 'L']
for tshirt in ('%s %s' %(c, s) for c in colors for s in sizes):
print(tshirt)
生成器表达式逐个产出元素,不会一次性产生一个含有特定数量元素的列表,从而避免额外的内存占用,所以更推荐使用这种方式!!!