LoginSignup
47
39

More than 5 years have passed since last update.

Pythonのlist, dict操作で覚えておきたいイディオム

Last updated at Posted at 2017-11-06

Pythonのlist, dictの操作で便利だけど意外に忘れられがちなイディオムをまとめた。

listの連結

2つのリストを連結してひとつにする。

lst1 = [1, 2, 3]
lst2 = [4, 5, 6]

lst3 = lst1 + lst2

print(lst3)

#
# [1, 2, 3, 4, 5, 6]
#

listの反転

Python3ではreversedを使うとイテレータが返ってくるので、list(reversed(lst))みたいにlist()で具現化しないといけなくて面倒。
sliceを使って書くのがスマート。

lst1 = [1, 2, 3, 4]

lst2 = lst1[::-1]

print(lst2)

#
# [4, 3, 2, 1]
#

2重listの転置

2重リストの行と列を入れ替える操作は1行で書ける。

lst = [[1, 2, 3], [4, 5, 6]]

lst = list(map(list, zip(*lst)))

print(lst)

#
# [[1, 4], [2, 5], [3, 6]]
#

一見複雑そうに見えるが、2段階に分けて考えると意外に単純。

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

一番外側のlist()はPython3でmap()の返り値でイテレータが返ってくるので具現化するためのもの。
Python2では map(list, zip(*lst))で良い。

dictのkey/valueを入れ替える

key->valueをvalue->keyに入れ替えるのは内包表記で書くのも良いが、個人的に一番簡潔だと思うのは以下のやり方。

d = {'a': 1, 'b': 2, 'c': 3}

d_inv = dict(zip(d.values(), d.keys()))

print(d_inv)

#
# {1: 'a', 2: 'b', 3: 'c'}
#

dictの合成

2つのdictを合成して新しい1つのdictを作る。
ただし、Python2だとこの書き方はできず、Syntax Errorになる。
3つ以上のdictの場合でも合成可能。

d1 = {'a': 1, 'b': 2}
d2 = {'c': 3, 'd': 4}

d3 = {**d1, **d2}

print(d3)

#
# {'a': 1, 'b': 2, 'c': 3, 'd': 4}
#

d1に破壊的操作を加えても良い場合は次の書き方もできる。

d1.update(d2)

print(d1)

#
# {'a': 1, 'b': 2, 'c': 3, 'd': 4}
#
47
39
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
47
39