python 自动生成动态变量及应用

python 自动生成动态变量及应用

在这里我们需要exec函数
exec(object[, globals[, locals]])
object:(必填)表示需要执行的Python代码
globals:(选填)表示全局命名空间 <字典>
locals:(选填)表示当前局部命名空间 <字典>

Example:生成10个变量
['q_0', 'q_1', 'q_2', 'q_3', 'q_4', 'q_5', 'q_6', 'q_7', 'q_8', 'q_9']

生成变量q_0到q_9,并赋值其平方数,代码如下

total=10
for i in range(total):
    exec('q_%d = %d' % (i ,i*i) ) 

输出结果:
在这里插入图片描述

未知变量数生成list

转换为list后我们就可以做更多的操作了

total=10
for i in range(total):
    exec('q_%d = %d' % (i ,i*i) ) 
    
value=[]
index=[]
for i in range(total):
    exec('value.append(q_%d)' % (i) )
    exec("index.append('q_%d')" % (i) )   
print('index:')
print(index)
print('value:')
print(value)

输出

index:
['q_0', 'q_1', 'q_2', 'q_3', 'q_4', 'q_5', 'q_6', 'q_7', 'q_8', 'q_9']
value:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
附表 常用格式符
格式符 作用
%s 字符串
%c 字符
%d 十进制整数
%o 八进制整数
%x 十六进制整数
%f 浮点数
%e 科学计数法

猜你喜欢

转载自blog.csdn.net/weixin_45760685/article/details/105068122