Transposed matrix in Python standard

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]]

Commentary

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]]

problem

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

Transposed matrix in Python standard
[Python] Find the transposed matrix in a comprehension
Matrix multiplication in python numpy
Matrix representation with Python standard input
Draw a scatterplot matrix in python
Make standard output non-blocking in Python
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
Meta-analysis in Python
Unittest in python
[Python] Standard input
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Find and check inverse matrix in Python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
[Python] Matrix operation
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Create a standard normal distribution graph in Python
Keep key names case in Python standard ConfigParser
How to output "Ketsumaimo" as standard output in Python
Identity matrix and inverse matrix: Linear algebra in Python <4>
Standard .py file used in Python trials (template)-2020
Matrix Calculations and Linear Equations: Linear Algebra in Python <3>
Flatten an irregular 2D standard list in Python
Daily AtCoder # 36 in Python
Clustering text in Python
Implement Enigma in python
Daily AtCoder # 32 in Python