LoginSignup
1
2

More than 3 years have passed since last update.

numpyを使わずにリストの転置

Last updated at Posted at 2019-06-05

わざわざnumpyをimportするまでもない時は以下の手順で転置できる。
(shiracamusさんにコメントを頂き、より簡潔に修正致しました。ありがとうございます。)

>>> A = [[1,2],[3,4],[5,6]]
>>> AT = [*zip(*A)]

>>> A
[[1, 2], [3, 4], [5, 6]]
>>> AT
[(1, 3, 5), (2, 4, 6)]

タプルになるのが気に入らないなら以下。

(1)
>>> AT = [[*a] for a in zip(*A)]
>>> AT
[[1, 3, 5], [2, 4, 6]]

(2)
>>> AT = [*map(list, zip(*A))]
>>> AT
[[1, 3, 5], [2, 4, 6]]

(3)
>>> *AT, = map(list, zip(*A))
>>> AT
[[1, 3, 5], [2, 4, 6]]

サクッと転置してfor文回したいときにオススメ。

余談。
以下が等価なのは凄い勉強になった。

>>> [*A]
[[1, 2], [3, 4], [5, 6]]
>>> list(A)
[[1, 2], [3, 4], [5, 6]]
1
2
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
2