Python 列表解析
1. 简单列表解析
假设我们需要创建一个列表为:[0,0,0,0,0,0, 0,0,0, 0](size=10)
显然这样写0很费劲。所以有一种叫做列表解析的东西可以快速生成:
>>> [0 for i in range(10)] [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
# 还可以按序生成 >>> [i for i in range(10)] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2. 带条件列表解析
假设我们需要创建一个列表:[0,2,0, 4, 0, 6, 0, 8, 0, 10] (size=10, 奇数为0,偶数不变)
>>> [i+1 if i%2 == 1 else 0 for i in range(10)] [0, 2, 0, 4, 0, 6, 0, 8, 0, 10]
note: 当条件子句在for前时必须带上else,此时else表示不符合if条件时列表元素的取值;当条件子句在for后时不能带上else。不然会报错!
>>> [i+1 if i%2 == 1 for i in range(10)] File "<input>", line 1 [i+1 if i%2 == 1 for i in range(10)] # if在前面时,必须有else ^ SyntaxError: invalid syntax >>> [i+1 for i in range(10) if i%2 == 1 else 0] File "<input>", line 1 [i+1 for i in range(10) if i%2 == 1 else 0] # if在后面时,不能有else ^ SyntaxError: invalid syntax
3. 多重循环的列表解析
假设我们需要根据创建一个列表:[(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)](可以看成(1, 2) 和 (1, 2, 3)的全排列)
>>> [(i, j) for i in [1, 2] for j in [1, 2, 3]] [(1, 1), (1, 2), (1, 3), (2, 1), (2, 2), (2, 3)] # perfect!
矩阵降维或者表量化:
>>> matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> array = [i for row in matrix for i in row] [1, 2, 3, 4, 5, 6, 7, 8, 9]
notes: 注意两个 for 的先后顺序:高维在前!
4.字典解析
假设我们想把列表:[(1, 201), (2, 202), (3, 205)],变成字典 {1: 201, 2: 201, 3: 205}
>>> {k: v for k, v in [(1, 201), (2, 201), (3, 205)]} {1: 201, 2: 201, 3: 205} # perfect!
任何大神都是从小白当起!