其他分享
首页 > 其他分享> > 动态式批量生成变量的方法

动态式批量生成变量的方法

作者:互联网

使用函数locals()

>>> for i in range(5):
...     locals()['X%s' % i] = ''
...
>>> print(X0,X1,X2,X3,X4)

>>> print(X5)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'X5' is not defined

还可以生成列表和字典:

>>> X1
0
>>> locals()['X%d' % 1] = []
>>> X1
[]
>>> A = []
>>> A
[]
>>> locals()['X%d' % 1] = {}
>>> X1
{}

 

标签:...,变量,批量,X%,print,X1,生成,locals,X5
来源: https://www.cnblogs.com/iBoundary/p/11406988.html