欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

How do you create different variable names while in a loop?

程序员文章站 2022-04-24 14:57:41
...

The question can be rephrased into something like
“How to create variables following the same format?”

For example purposes…

for x in range(0,9):
    string'x' = "Hello"

Python 3.6+

The original link can be found here

  • Using dictionary in Python (RECOMMEND)
d = {}
for x in range(1, 10):
    d["string{0}".format(x)] = "Hello"
>>> d["string5"]
'Hello'
>>> d
{'string1': 'Hello',
 'string2': 'Hello',
 'string3': 'Hello',
 'string4': 'Hello',
 'string5': 'Hello',
 'string6': 'Hello',
 'string7': 'Hello',
 'string8': 'Hello',
 'string9': 'Hello'}
  • Using exec
for k in range(5):
    exec(f'cat_{k} = k*2')
>>> print(cat_0)
0
>>> print(cat_1)
2
>>> print(cat_2)
4
>>> print(cat_3)
6
>>> print(cat_4)
8
相关标签: python