python变量列表,按变量名称检索变量的值 [英] python list of variables, retrieve value of variable by variable name
问题描述
如果我有代码:
attRoll = 34
hit = False
dmg = 1
attSequence = [attRoll, hit, dmg]
print attSequence[dmg]
它打印hit(False)而不是dmg(1)的值,我可以通过输入以下内容来解决此问题:
it prints the value of hit (False) and not dmg (1), i can work around this by entering:
print attSequence[dmg+1]
我的问题:
-为什么不显示dmg的值?
- 是否有一种干净的方法(没有 +1)来检索命中值?
my questions:
-why doesn't it print the value of dmg?
-is there a clean way (without the +1) to retrieve the value of hit?
谢谢!
推荐答案
attSequence
是一个列表,而 dmg
是1,所以 attSequence [1]
的意思是给我 attSequence
中索引1的项目(第二个项目)".对于您正在做的事情,您可能需要词典(通常称为使用其他语言的地图),它存储键/值映射,因此可以使用密钥"dmg":
attSequence
is a list, and dmg
is 1, so attSequence[1]
means "Give me the item at index 1 (the second item) in attSequence
". For what you're doing, you probably want a dictionary (usually called a map in other languages), which stores key/value mappings, so you could store the damage with a key of "dmg":
att = {
"roll": attRoll,
"hit": hit,
"dmg": dmg
}
print att["dmg"]
您也可以在地图上放置文字,因此您可以这样做:
You can also put literals in a map, so you could do this:
att = {
"roll": 34,
"hit": False,
"dmg": 1
}
这篇关于python变量列表,按变量名称检索变量的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!