7.3 Python列表生成式详解

深入学习Python列表生成式(List Comprehensions)的使用方法,包括基本语法、条件筛选、嵌套循环、字符串处理等高级特性,掌握Python高效数据处理的核心技巧。

列表生成式(List Comprehensions)是Python内置的强大功能,能用简洁的方式创建list。

生成 [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 可以用 list(range(1, 11))

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

但要生成 [1x1, 2x2, 3x3, ..., 10x10] 怎么办?用循环:

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

写列表生成式时,把要生成的元素 x * x 放前面,后面跟 for 循环,list就创建出来了。这语法很实用,多写几次就熟悉了。

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

三层及以上的循环就很少用了。

列表生成式能写出非常简洁的代码。比如列出当前目录下的所有文件和目录,一行搞定:

>>> import os # 导入os模块,模块的概念后面讲到
>>> [d for d in os.listdir('.')] # os.listdir可以列出文件和目录
['.emacs.d', '.ssh', '.Trash', 'Adlm', 'Applications', 'Desktop', 'Documents', 'Downloads', 'Library', 'Movies', 'Music', 'Pictures', 'Public', 'VirtualBox VMs', 'Workspace', 'XCode']

for 循环能同时使用两个甚至多个变量。比如 dictitems() 能同时迭代key和value:

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

列表生成式也能用两个变量生成list:

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

把list中所有字符串变成小写:

>>> L = ['Hello', 'World', 'IBM', 'Apple']
>>> [s.lower() for s in L]
['hello', 'world', 'ibm', 'apple']

if … else

用列表生成式时,if...else 的用法容易搞混。

比如这段代码正常输出偶数:

>>> [x for x in range(1, 11) if x % 2 == 0]
[2, 4, 6, 8, 10]

但在最后的 if 加上 else 就报错了:

>>> [x for x in range(1, 11) if x % 2 == 0 else 0]
  File "<stdin>", line 1
    [x for x in range(1, 11) if x % 2 == 0 else 0]
                                              ^
SyntaxError: invalid syntax

因为跟在 for 后面的 if 是筛选条件,不能带 else。想想看,筛选条件带 else 还怎么筛?

if 写在 for 前面就必须加 else,不然报错:

>>> [x if x % 2 == 0 for x in range(1, 11)]
  File "<stdin>", line 1
    [x if x % 2 == 0 for x in range(1, 11)]
                       ^
SyntaxError: invalid syntax

因为 for 前面的部分是个表达式,必须根据 x 算出一个结果。表达式 x if x % 2 == 0 没法算出结果,缺了 else。加上 else 就对了:

>>> [x if x % 2 == 0 else -x for x in range(1, 11)]
[-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]

这样 for 前面的表达式 x if x % 2 == 0 else -x 才能根据 x 算出确定的结果。

总结一下:列表生成式里,for 前面的 if ... else 是表达式,for 后面的 if 是过滤条件,不能带 else

练习

如果list中既有字符串又有整数,非字符串类型没有 lower() 方法,列表生成式会报错:

>>> L = ['Hello', 'World', 18, 'Apple', None]
>>> [s.lower() for s in L]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <listcomp>
AttributeError: 'int' object has no attribute 'lower'

用内建的 isinstance 函数可以判断变量是不是字符串:

>>> x = 'abc'
>>> y = 123
>>> isinstance(x, str)
True
>>> isinstance(y, str)
False

修改列表生成式,通过添加 if 语句让它能正确执行:

L1 = ['Hello', 'World', 18, 'Apple', None]
L2 = ???

# 测试:
print(L2)
if L2 == ['hello', 'world', 'apple']:
    print('测试通过!')
else:
    print('测试失败!')

小结

列表生成式能快速生成list,用一个list推导出另一个list,代码还很简洁。