在for循环python中打印变量

时间:2020-08-18 21:09:36

标签: python-3.x for-loop printf

我希望输出为变量而不是其值。下面的代码给我输出为 “什么” “为什么” “什么时候” “哪里” 但我希望输出为 一种 b C d

public class AggregateA {
    public AggregateC createAggregateC(...){
        //create AggregateC and return it with reference set to AggregateA
        return new AggregateC(this.id, ...)
    }
}

2 个答案:

答案 0 :(得分:0)

那是不可能的。如果您还想跟踪名称,则应使用dict:

words = { "a": "what", "b": "why", "c": "when", "d": "where" }

for x in words.keys():
    print(x)

打印出变量名的唯一方法是3.8中的新调试格式设置选项:

print(f"{x=}")

这将导致类似

x = 5

答案 1 :(得分:0)

https://docs.python.org/3/library/inspect.html

import inspect


def retrieve_variable_name(value):
    for var, val in inspect.currentframe().f_back.f_locals.items():
        if val is value:
            return var


a = "what"
b = "why"
c = "when"
d = "where"

A = [a, b, c, d]
for x in A:
    print(retrieve_variable_name(x))