列表生成式list comprehensions,是Python内置的非常简单却强大的可以用来创建list的生成式。
举例,要生成list[1,2,3,4,5,6,7,8,9]可以用list(range(1,10)):
>>> list(range(1,10))
[1,2,3,4,5,6,7,8,9]
>>> [x * x for x in range(1,11)]
[1,4,9,16,25,36,49,64,81,100]
for 循环后面还可以加上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']