[英]How to print variable name in a list
So i just want to print the variable's name.所以我只想打印变量的名称。 you can see from the case below
你可以从下面的案例中看到
Andi = 100
Bill = 50
Kira = 90
List1 = [Andi, Bill, Kira]
for i in List1:
print(i) # Here the problem, i want the Variable Name and Value printed together
So guys i got this code from user, name "Anna Nevison".所以伙计们,我从用户那里得到了这个代码,名字是“Anna Nevison”。 i wanted to accept her answer, but she delete her post so i post her code here :)
我想接受她的回答,但她删除了她的帖子,所以我在这里发布了她的代码:)
Andi = 100
Bill = 50
Kira = 90
List1 = ['Andi', 'Bill', 'Kira']
for i in List1:
print(i, eval(i))
You can't do this with plain variables.你不能用普通变量来做到这一点。 Use a dictionary instead:
改用字典:
mydict = {
'Andi': 100,
'Bill': 50,
'Kira': 25
}
for name in mydict:
print(name, mydict[name])
Maybe you should consider using something like a dictionary instead?也许您应该考虑使用诸如字典之类的东西?
people = {
"Andi": 100,
"Bill": 50,
"Kira": 90
}
Then you can access the values associated with the dictionary's key like so:然后您可以像这样访问与字典键关联的值:
print(people["Andi"]) # returns 100
Or you can iterate through the dictionary and print all of the values like so:或者您可以遍历字典并打印所有值,如下所示:
for person, number in people.items():
print(f'{person}: {number}')
Of course the name 'person' for the variable could be something else... I just didn't know what the numbers in your example are.当然,变量的名称“人”可能是别的东西......我只是不知道你的例子中的数字是什么。
Hope that helps!希望有帮助!
Maybe these code could help:也许这些代码可以帮助:
Dict_var = dict({"Andi" : 100, 'Bill' : 50, "Kira" : 90})
for i,j in Dict_var.items():
print(i,":",j)
For multiple keys and values:对于多个键和值:
keys = ['Andi', 'Bill', 'Kira']
values = [100, 50, 90]
Dict_var = dict(zip(keys,values))
for i,j in Dict_var.items():
print(i,":",j)
And the result could be like this:结果可能是这样的:
Andi : 100
Bill : 50
Kira : 90
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.