3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonのzip関数について

Posted at

#はじめに
普段pythonを使っていて個人的に馴染みがなかったzip関数について知ったことをメモ

#zip関数の挙動
ばらけた要素をまとめたり,別々のリストを同時にループさせたりする時に便利

data_num = [1,2,3,4,5]
data_ch = ["a","b","c","d","e","f"]
for num,ch in zip(data_num,data_chr):
    print(num,ch)
>>> 1 a
    2 b
    3 c
    4 d
    5 e

このように別々の変数を同時に回せる.リストの長さが異なる場合は短い方のリストの中身が尽きれば終了する.

#zip関数と逆の挙動
この通常のzip関数の挙動と逆の挙動をやりたいときはどうするのか
例えば

>>> data = [[1,"a"],[2,"b"],[3,"c"],[4,"d"]]
>>> nums,chs = zip(*data)
>>> nums # [1,2,3,4]
>>> chs  # ["a","b","c","d"]

とすることで実現できる.
これを用いると行列の回転がすごい楽である
まあnumpy使えやって話ですが

#行列の回転
以上のことを踏まえて行列を時計回りに90度回転させてみる

matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
turned_matrix = zip(*matrix[::-1]) #[(7, 4, 1), (8, 5, 2), (9, 6, 3)]

一行でpythonのリストでも行列の回転ができてしまった.(すごい)

3
4
0

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
3
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?