简体   繁体   English

如何打印出变量名而不是值?

[英]How to print out variable name instead of value?

If I have a list of variables and each variable is assigned to an equation, how can I print the variable itself from the list not the result of the equation如果我有一个变量列表并且每个变量都分配给一个方程式,我如何从列表中打印变量本身而不是方程式的结果

For example:例如:

x = 1 + 1
y = 2 + 2
z = 3 + 3

list = [x, y, z]

print(list[0])
print(list[1])
print(list[2])

Should print out:应该打印出来:

x
y
z

Instead of:代替:

2
4
6

print() giving you a values of list[0], or list[1] or list[2] You gave them values 2,4,6 at the start of your app print() 给你一个列表 [0] 或列表 [1] 或列表 [2] 的值 你在你的应用程序开始时给了他们值 2,4,6

x = 1 + 1
y = 2 + 2
z = 3 + 3

if you want to get x,y,z try this:如果你想得到 x,y,z 试试这个:

x = "x"
y = "y"
z = "z"

in that case, you will need to change your list to a string, otherwise it will think that it is a variable and print the value assigned to it.在这种情况下,您需要将列表更改为字符串,否则它会认为它是一个变量并打印分配给它的值。 to fix this you change line 5 to: list = ["x","y","z"] -> this way it will print out the string, not the value of the variable x要解决此问题,请将第 5 行更改为:list = ["x","y","z"] -> 这样它将打印出字符串,而不是变量 x 的值

The answers here are obviously correct, but perhaps they miss the real point.这里的答案显然是正确的,但也许他们没有抓住重点。 I presume you want to be able to show/use both the names and the values, for instance print something like "the sum of x, y, z is 12".我假设您希望能够显示/使用名称和值,例如打印类似“x、y、z 的总和为 12”之类的内容。

If this is the case you may want to work with Python's builtin namespaces, but the simplest thing is to use a dictionary where your names will be the keys and your values... well, the values:如果是这种情况,您可能希望使用 Python 的内置名称空间,但最简单的方法是使用字典,其中您的名称将是键,您的值……好吧,值:

my_dict = {}
my_dict['x'] = 1 + 1
my_dict['y'] = 2 + 2
my_dict['z'] = 3 + 3

','.join(my_dict.keys()) #'x,y,z'
sum(my_dict.values()) # 12

From your first question i didn't understand well what do you need从你的第一个问题开始,我不太明白你需要什么

I think this can work:我认为这可以工作:

def dna_content(seq):
    A = ["A", (seq.count("A") / len(seq)) * 100]

    T = ["T", (seq.count("T") / len(seq)) * 100]
    G = ["G", (seq.count("G") / len(seq)) * 100]
    C = ["C", (seq.count("C") / len(seq)) * 100]
    bases = [A, T, G, C]
    for i in bases:
        print(str(i[0]) + " content is: " + str(i[1]))

And... i couldn't find how to acces name of variable through it's value而且......我找不到如何通过它的值访问变量的名称

UPD:更新:

try this:尝试这个:

x = 1 + 1
y = 2 + 2
z = 3 + 3
list = ["x", "y", "z"]


for i in list:
    print(i, globals()[i])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM