You can use zip.
>>> matrix = [
... [1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]
... ]
>>> list(map(list, zip(*matrix)))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
If you add *
when passing an iterable object to a function, it will be expanded and passed.
So zip (* matrix)
and zip ([1, 2, 3], [4, 5, 6], [7, 8, 9])
are equivalent.
And if it is list (zip (* matrix))
, the contents will be tuples, so convert it to list using map.
>>> list(zip(*matrix))
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> list(map(list, zip(*matrix)))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
With this method, an error will occur when there is only one line.
>>> matrix = [1, 2, 3]
>>> list(map(list, zip(*matrix)))
TypeError: zip argument #1 must support iteration
I don't know how many opportunities a row has to deal with a one-row matrix in the first place.
(Addition)
In the case of one line, you can do it without adding *
.
>>> matrix = [1, 2, 3]
>>> list(map(list, zip(matrix)))
[[1], [2], [3]]
Recommended Posts