Created
October 4, 2015 14:47
-
-
Save poros/d66a00dc61fea307cfb7 to your computer and use it in GitHub Desktop.
Nested list comprehensions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
matrix = [[1,2,3]] * 4 | |
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]] | |
# FLATTEN THE MATRIX | |
flatten = [] | |
for row in matrix: | |
for i in range(3): | |
flatten.append(row[i]) | |
[row[i] for row in matrix for i in range(3)] | |
[1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3] | |
# equivalent to | |
from itertools import chain | |
list(chain(*matrix)) | |
list(chain.from_iterable(matrix)) | |
# TRANSPOSE THE MATRIX | |
[[row[i] for row in matrix] for i in range(3)] | |
[[1, 1, 1, 1], [2, 2, 2, 2], [3, 3, 3, 3]] | |
# almost equivalent to | |
zip(*matrix) | |
[(1, 1, 1, 1), (2, 2, 2, 2), (3, 3, 3, 3)] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment