LoginSignup
1
1

More than 5 years have passed since last update.

2次配列を転置したい

Last updated at Posted at 2017-11-26

Pythonで2次配列の転置行列 (x軸、y軸を入れ替える) の作り方。
毎回調べなおしてるので、めもめも。

>>> matrix = [
...   [ 11, 12, 13 ],
...   [ 21, 22, 23 ]
... ]

>>> for l in matrix:
...   print l
... 
[11, 12, 13]
[21, 22, 23]

>>> transposed = list(zip(*matrix))

>>> for l in transposed:
...   print l
... 
(11, 21)
(12, 22)
(13, 23)

Python 2.x系

Python 2.x系だと↓だけで期待した結果になります。

>>> zip(*matrix)
[(11, 21), (12, 22), (13, 23)]

なんでこうなるかというと Python 2.x系 と 3.x系 は zip() functionの動きが異なるのが原因です。

tupleじゃなくてlistで

tuple のままだと都合が悪い時は map() を使います。

>>> map(list, zip(*matrix))
[[11, 21], [12, 22], [13, 23]]
1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1