列表解析中的第一个表达式可以是任何表达式,包括列表解析。
考虑下面由三个长度为 4 的列表组成的 3x4 矩阵:
1 2 3 4 5
| >>> matrix = [ ... [1, 2, 3, 4], ... [5, 6, 7, 8], ... [9, 10, 11, 12], ... ]
|
现在,如果你想交换行和列,可以用嵌套的列表推导式:
1 2
| >>> [[row[i] for row in matrix] for i in range(4)] [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
|
像前面看到的,嵌套的列表推导式是对 for 后面的内容进行求值,所以上例就等价于:
1 2 3 4 5 6
| >>> transposed = [] >>> for i in range(4): ... transposed.append([row[i] for row in matrix]) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
|
反过来说,如下也是一样的:
1 2 3 4 5 6 7 8 9 10
| >>> transposed = [] >>> for i in range(4): ... ... transposed_row = [] ... for row in matrix: ... transposed_row.append(row[i]) ... transposed.append(transposed_row) ... >>> transposed [[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
|
在实际中,使用内置函数组成复杂流程语句。对此种情况zip()
函数将会做的更好:
1 2
| >>> list(zip(*matrix)) [(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]
|