2
1

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.

似た名前の変数を使うよりも辞書機能を使おう

Last updated at Posted at 2018-08-06

私はPythonの辞書機能を最近まで使いこなせていませんでした.

例えば0,1,2回目でseedの値を変えようとする時,
これまでは以下のように作っていました.

seed0 = 0
seed1 = 1
seed2 = 2

変数の数がどんどん増えるとややこしくなるので,
こうした場合に辞書機能を使うと分かりやすくなると思います.

辞書を使おう

辞書を使うと,以下のようにseedsという1つの辞書変数にまとめることが出来ます.

In:
seeds = dict()
for i in range(3):
    seeds[i] = i 
print(seeds)
Out:
{0: 0, 1: 1, 2: 2}

これは以下のように簡単に書けます.

{i: i for i in range(3)}

「seed1とかseed2などの名前が欲しいなぁ」という場合は,
Keyを活用すればより要求に近い形になるでしょう.

In:
seeds = {}
for i in range(3):
    seeds['seed%0d' % i] = i
for key, value in sorted(seeds.items()):
    print(key, value)
Out:
seed0 0
seed1 1
seed2 2

注意:local()を使う

local()を使ってローカル変数にアクセスすることは可能ですが危険です.

for i in range(3):
    locals()['seed{0}'.format(i)] = i

既にある似た名前の変数をリストにまとめたい時

test1,test2,test3という別々の変数があったとします.
(そもそも辞書を作って1つの変数にしとけよ・・・というツッコミは今は考えないことにします)
やりたい事は,

test0 = 0
test1 = 1
test2 = 2

から,tests = [0,1,2]を作ることです.

解決策

eval()を使います.

tests = [eval("test%d" % (i)) for i in range(3)] 
print(tests)
# tests = [0,1,2]

但し,eval()を使うことは好ましくありません.
理由がはっきりと分かっていませんが,eval()はlocal()探しに行くが,他で同じ名前のtest1があった時に混乱してしまうから,と理解しています.
やはり,もともと辞書を最初に作っておく事が大切なんですね.

追記

shiracamusさん,Sh1maさんからコメントを頂き,一部更新しました.

2
1
4

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?