字符串与变量名相同并根据字符串取出对应变量的值

a_1 = 1
a_2 = 2
a_3 = 3


def foo(str, a_i):
    # print((type(a_i)))
    print(str, a_i)


for i in range(1, 4):
    variable = "a_" + "{i}".format(i=i)
    foo("locals()", locals()[variable])  # 字符串与变量名相同并根据字符串取出对应变量的值
    foo("eval", eval(variable))
    foo("vars()", vars()[variable])

 

 

结果:

locals() 1
eval 1
vars() 1
locals() 2
eval 2
vars() 2
locals() 3
eval 3
vars() 3

 

可以参考:

https://blog.csdn.net/ztf312/article/details/51122027

你可能感兴趣的:(python)