List comprehension in python
It’s an interesting simple algorithm for understanding list comprehension in python3.
Here we got a matrix below, how can we get transposed matrix without any API methods or functions?
matrix = [ [1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12]]
Here is a fantasy solution in one line
[[row[i] for row in matrix] for i in range(len(matrix[0]))]`
[[1, 5, 9], [2, 6, 10], [3, 7, 11], [4, 8, 12]]
How does this work? I think it’s a liitle tricky to understand this command, so before understanding it thoroughly, we can begin it from a simple one.
Problem: how to flatten the origin matrix to [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
solution
[row[i] for row in matrix for i in range(len(matrix[0]))]
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Maybe you will find something familiar, YES, the solutions of flatten matrix and transpose matrix have striking similarity!
[[row[i] for row in matrix] for i in range(len(matrix[0]))] ##transpose
[ row[i] for row in matrix for i in range(len(matrix[0]))] ##flatten
Well, you now can clearly see the difference, let’s explain the flatten first.
flatten_list = []
for row in matrix:
for i in range(len(maxtrix[0])):
flatten_list.append(row(i))
The solution for flatten is equivalent to code above, it’s not hard to understand, there are 2 for in loop.
transpose_list = []
for i in range(len(maxtrix[0])):
transpose_row = []
for row in matrix:
transpose_row.append(row(i))
transpose_list.append(transpose_row)
Above is equivalent to transposed solution, which is a liitle more complicated comparing with the other, because list comprehension(1st is for i in range(…)) is nested by another list comprehension (2nd is for row in matrix), conversely, solution for flatten is only one list comprehension, please take care of the difference.