LoginSignup
4
5

More than 3 years have passed since last update.

Pythonで変数を動的に定義する方法

Posted at

概要

  • Pythonで変数を動的に定義する方法を紹介
  • execで動的に変数を定義する
    • ただし、日本語等マルチバイト文字はエラーがでるため少し工夫した。

用途

  • ユーザーが好き勝手名称を定義するので、何とかしたかった。

ソースコード


# ユーザーの適当Input
header_list = ['ほげほげ', 'ふがふが', 'ほげふが']
vars = [25.7,13.2,12.5]

coef_list = []
for no,(header,var) in enumerate(zip(header_list,vars)):
    coef_list.append(dict(name = 'coef'+str(no),header=header,var=var))

# output
# サンプル係数辞書(dict型)
print(coef_list)

>> [{'name': 'coef0', 'header': 'ほげほげ', 'var': 25.7},
    {'name': 'coef1', 'header': 'ふがふが', 'var': 13.2},
    {'name': 'coef2', 'header': 'ほげふが', 'var': 12.5}]
# dict型からnameとvarを取り出して、変数として定義する。
for coef in coef_list:
    exec('{name} = {var}'.format(name = coef['name'], var = coef['var']))

print(coef0)
print(coef1)
print(coef2)

# output
>> 25.7
>> 13.2
>> 12.5
4
5
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
4
5