[英]Dictionnary Python variable
I want use a variable as dictionnary name for find and use fastly some values.我想使用一个变量作为字典名称来快速查找和使用一些值。 (For example i want the agressivity of my fighter one).
(例如,我想要我的战斗机的攻击性)。 I use a variable because the fighter can change and i want a dynamic script.
我使用一个变量,因为战斗机可以改变,我想要一个动态脚本。
fighter1 = {"agressivity": 6, "agility": 2}
agressivity = 0
arenafighter = "fighter1"
agressivity = arenafighter["agressivity"]
But i have the same problem "TypeError: string indices must be integers"但我有同样的问题“TypeError:字符串索引必须是整数”
You can use a dict in a dict您可以在字典中使用字典
fighters = {
"fighter1": {"agressivity": 6, "agility": 2},
"fighter2": {"agressivity": 8, "agility": 4},
}
arenafighter = "fighter1"
agressivity = fighters[arenafighter]["agressivity"]
I believe the problem with your code is that when defining arenafighter you put fighter1 in quotes, which makes the value of arenafighter into the word "fighter1" because it is a string.我相信您的代码的问题在于,在定义 arenafighter 时,您将 fighter1 放在引号中,这使得 arenafighter 的值变成了单词“fighter1”,因为它是一个字符串。
Try this:尝试这个:
fighter1 = {"agressivity": 6, "agility": 2}
agressivity = 0
arenafighter = fighter1
agressivity = arenafighter["agressivity"]
Why don't you make a dictionary with all fighters?你为什么不把所有的战士都编成一本字典呢? It could look like this:
它可能看起来像这样:
fighters = {
"fighter_1": {"agressivity": 6, "agility": 2},
"fighter_2": {"agressivity": 5, "agility": 4}
}
by doing that now you can access fighters like this:通过这样做,你现在可以像这样访问战士:
fighter = "fighter_1"
print(fighters[fighter]["agressivity"])
What you need is some simple class and object creation.您需要的是一些简单的 class 和 object 创建。 B'coz you say the fighter can change and you want to dynamically assign values for each fighter..see if this code helps
因为你说战士可以改变,你想为每个战士动态分配值..看看这段代码是否有帮助
class Fighter:
def __init__(self,name,agressivity,agility):
self.name = name
self.agressivity = agressivity
self.agility = agility
fighter1 = Fighter(fighter1, 6, 2)
print(fighter1.agressivity)
arenafighter = Fighter(arenafighter, 0, 2)
print(arenafighter.agressivity)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.