1. 推导式通常可转换为for循环
简单的for循环通常可以使用推导式来替换:
>>> [(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)]它实际上等价于:
>>> combs = []>>> for x in [1, 2, 3]: for y in [3, 1, 4]: if x != y: combs.append((x, y)) >>> combs[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
2. 推导式往往可完成复杂的for循环表示(不推荐)
以下代码将逆转一个矩阵:
>>> 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]]它可以先被分解为:
>>> 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]]进一步被分解为:
>>> 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函数也可以达到同样的效果:
>>> zip(*matrix)[(1, 5, 9), (2, 6, 10), (3, 7, 11), (4, 8, 12)]