# Python 列表生成式

``` range(1,11)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]```

``` L = []
for x in range(1, 11):
...     L.append(x*x)
...
L
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]```

``` [ x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]```

`[process(x) for x in L if should_keep(x)]`

1、将需要生成的内容放入x * x

2、后面跟上for循环起来

for循环后面还能添加if判断，例如：筛选出偶数的平方

``` [x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]```

``` [m + n for m in 'ABCD' for n in 'XYZ']
['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ', 'DX', 'DY', 'DZ']```

for循环可以同时两个或者多个变量，比如dict和iteritems()可以同时迭代key和value：

``` d = {'x':'A', 'y':'B', 'z':'C'}
for k, v in d.iteritems():
...     print k, '=', v
...
y = B
x = A
z = C```

``` d = {'x':'A', 'y':'B', 'z':'C'}
[k + '=' + v for k, v in d.iteritems()]
['y=B', 'x=A', 'z=C']```

`L = ['Hello', 'World', 18, 'Apple', None]`

1、有字符串，有数字，如果直接用s.lower()进行更改会出现错误，因为整数非字符串类型

2、可以使用内建的isinstance函数判断一个变量是否为字符串

3、要根据这个原型进行调整：[process(x) for x in L if should_keep(x)]

4、process(x) 等于 s.lower() if isinstance(s, str) else s ；后面按正常走：(**不懂可以看备注1）

` [s.lower() if isinstance(s,str) else s for s in L]`

``` [s.lower() if isinstance(s,str) else s for s in L]
'hello', 'world', 18, 'apple', None]```

1、没有出现整数

``` [L.lower() for L in L if isinstance(L, str)]
['hello', 'world', 'apple']```

` [s.lower() for s in L if isinstance(s, str) else s for s in L]`

• 06:10:02
• 01:33:32
• 02:12:07
• 03:07:31
• 03:37:22
• 01:54:51