Help us understand the problem. What is going on with this article?

2次配列を転置したい

More than 1 year has passed since last update.

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]]
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした