4
3

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.

pythonのfor文中で複数の変数を定義する方法

Posted at

for文で変数名を変えながら定義する方法ってどうやるんだ? となったのでメモ

python の組み込み関数 exec を使う

for i in range(5):
    exec('var%d = %d' % (i, i**2))

>>>var0, var1, var2, var3, var4
>>>(0, 1, 4, 9, 16)

他にも配列に入れていくやり方が考えられますが、一気に複数の変数を作るならexecを使うのがスマート。

4
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?