LoginSignup
12
14

More than 5 years have passed since last update.

Python > zip(*list4) > 行列の変換 > リストやタプルの引数展開 / 辞書引数展開 / ローカル変数辞書 locals()

Last updated at Posted at 2017-03-23
動作環境
Xeon E5-2620 v4 (8コア) x 2
32GB RAM
CentOS 6.8 (64bit)
openmpi-1.8.x86_64 とその-devel
mpich.x86_64 3.1-5.el6とその-devel
gcc version 4.4.7 (とgfortran)
NCAR Command Language Version 6.3.0
WRF v3.7.1を使用。
Python 2.6.6 (r266:84292, Aug 18 2016, 15:13:37) 
Python 3.6.0 on virtualenv

関連 http://qiita.com/7of9/items/d7bc7038a697adb214ee#comment-1a85846225c5085f851a

test_python_170323.py
list4 = [
    [ 1, 2, 3],
    [ 4, 5, 6],
    [ 7, 8, 9]
]

for cols in zip(*list4):
    print(cols)
$ python test_python_170323.py 
(1, 4, 7)
(2, 5, 8)
(3, 6, 9)

行と列が変換されているように思われる。

何を行っているのだろうか。

注目すべきは zip(*pair)の部分です。zipの引数の前にアスタリスクがついています。
関数呼び出しの引数の前についているアスタリスクは、公式ドキュメントにもあるように展開されて解釈されます。

上記のzip(*list4)は以下と同じになるのだろう。

for cols in zip((1,2,3),(4,5,6),(7,8,9)):
    print(cols)
>>> help(zip)
zip(...)
    zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]

    Return a list of tuples, where each tuple contains the i-th element
    from each of the argument sequences.  The returned list is truncated
    in length to the length of the shortest argument sequence.

を見ると、展開された結果の(1,2,3),(4,5,6),(7,8,9)において、i-th element(例: (i==0)の時は(1,4,7)のセット)がtupleとなる。

結果として、行列の変換のような機能になる。

教えていただいた事項

@shiracamus さんのコメントにおいて、以下の事項を教えていただきました。

  • リストやタプルの引数展開 (*)
  • 辞書引数展開 (**)
  • ローカル変数辞書 (locals())
    • locals()は過去にコメントで教えていただいていました (まだ身についてません)
12
14
3

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
12
14