python最基础学习(四)列表生成式

1.例一:

>>> for x in range(1,10):

...    L.append(x*x)

>>> L

[1, 4, 9, 16, 25, 36, 49, 64, 81]

但是循环太繁琐,而列表生成式则可以用一行语句代替循环生成上面的list:

>>> [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']

>>> d = { 'x':'a','y':'b','z':'c'}

>>> for k,v in d.items():

...    print(k, '=', v)

x = a

y = b

z = c

你可能感兴趣的:(python最基础学习(四)列表生成式)