传递字符串以打印变量

时间:2019-04-19 14:11:45

标签: python-3.x

我有多个变量,它们的值我希望通过字符串的输出访问。我可以获取字符串值,但不知道如何转换字符串“ P2”,因此可以打印或访问变量P2的内容。

正在寻找打印列表的不同方法,并一直使用for循环,但我迷路了,找不到解决方法。

P1 = [1.123, 10.34, 48.61]
P2 = [2.22, 11.34, 49.61]
P3 = [3.32, 12.34, 50.61]

g_line = ["N30","G54.1","P2",";\n"] 

def work_zero_p_num(): 
    for k, line in enumerate(g_line):
        if "P" in line:
            get_cur_work = line
    print(get_cur_work) # This line prints value "P2", 

work_zero_p_num()

我想要的输出是;

print(P2)
[2.22, 11.34, 49.61]

我从代码中得到的是

print(get_cur_work)
P2

2 个答案:

答案 0 :(得分:0)

您可以使用globalslocals来检索变量作为dict。

P1 = [1.123, 10.34, 48.61]
P2 = [2.22, 11.34, 49.61]
P3 = [3.32, 12.34, 50.61]

g_line = ["N30","G54.1","P2",";\n"] 

def work_zero_p_num(): 
    for k, line in enumerate(g_line):
        if "P" in line:
            get_cur_work = line
    print(globals()[get_cur_work]) # This line prints the value of P2, 

work_zero_p_num()

可以找到更详细的答案here

答案 1 :(得分:0)

通过内置函数查看globals()和id(): https://docs.python.org/3/library/functions.html#built-in-functions

示例:

def objname(obj):
    return [name for name, object_id in globals().items()
        if id(object_id) == id(obj)][0]

P2 = [2.22, 11.34, 49.61]


>>> print(P2)
[2.22, 11.34, 49.61]
>>> objname(P2)
'P2'
>>> print(objname(P2))
P2

您可能还对其他功能感兴趣,例如: locals(),type(),dir(),getattr(),hasattr(),callable()