LoginSignup
0
2

More than 5 years have passed since last update.

任意の数の変数をforで自動生成して代入

Posted at

使用する変数の数が、inputで与えられるとき・毎回変わるが関数化したいとき等に、
for文を使用して、任意の数の変数を作成し、値も代入できるようにしました。

>>> #name0, name1, name2 の変数の作成、0を代入
...for i in range(0, 3):
...    exec("name%d = %d" %(i, 0))

>>> name0
0
>>> name1
0
>>> name2
0

応用

キー、バリュー、それぞれのリストのindexごとのペアを辞書にしました

>>> #キーにするリストの作成
... keys = ['b', 'c', 'd']
>>> keys
['b', 'c', 'd']

>>> #バリューにするリストの作成
... values = [2, 3, 4]
>>> values
[2, 3, 4]


>>> #辞書の作成
... d = {'a':1}
>>> #辞書にキーバリューの追加({keys[i]:values[i]}のペアを追加していく)
...for i in range(0, len(keys)):
...   exec("d[keys[%d]] = values[%d]" %(i, i))

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

0
2
2

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