列表推导式(list comprehension)是一种方便简介的语法形式,我们可以利用它将一个列表经过过滤后转换成另一个列表,也可以利用它将函数应用于列表中的元素。列表推导式如以下书写形式:
[表达式 for 变量 in 列表]
或者:
[表达式 for 变量 in 列表 if 条件]
例如:
>>>[x**2 for x in range(5)]
[0,1,4,9,16]
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
>>> from math import pi
>>> [str(round(pi, i)) for i in range(1, 6)]
['3.1', '3.14', '3.142', '3.1416', '3.14159']
>>> vec = [[1,2,3], [4,5,6], [7,8,9]]
>>> [num for elem in vec for num in elem]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
同时也可以进行嵌套:
>>> matrix = [
... [1, 2, 3, 4],
... [5, 6, 7, 8],
... [9, 10, 11, 12],
... ]
>>> [[row[i] for row in matrix] for i in range(4)]
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]