LoginSignup
8
6

More than 5 years have passed since last update.

Pythonでlistをキーにしたdictを使う

Posted at

Pythonでは、list型は辞書のキーにすることができません。

key = [1, 2, 3]
table = {key: 1}  # エラー

なぜかというと、list型は状態を変えられるからです。例えば

key1 = [1]
key2 = [2]
table = {key1: 1, key2: 2}
key1[0] = 2

とかできちゃったら困りますよね。でも配列をキーにしたい!そんなときにはtupleを使いましょう。

ライブラリ

独自の配列を扱うライブラリとしては、numpyとsympyがあります。これらでの扱いはどうなっているでしょうか?
あるオブジェクトをキーにできるかは__hash__関数があるかどうかで決まっているので、見てみましょう。

from sympy import Matrix, ImmutableMatrix
import numpy as np

# sympy
Matrix([1, 2]).__hash__  # None
ImmutableMatrix([1, 2]).__hash__  # not None

# numpy
a = np.array([1, 2])
a.__hash__  # None
a.flags.writeable = False
a.__hash__  # None

ということで、numpyでは書き込み不可にしてもダメでした。まあ、戻せちゃうので当たり前ですけど。。
(ちなみにsympyのas_immutableなどではコピーができるっぽいです。元のに変更を加えてもできたものは変わりません。)

8
6
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
8
6