如何将变量(或数组等)名称合并到另一个东西的名称中?

时间:2016-04-16 22:08:07

标签: python python-3.x

我想创建一个名称包含名称kaiylarScore的变量,但下面的代码不起作用。

firstName = input("What's your first name? ")
firstName + "Score" = score

我想这样做,例如,如果输入print(kaiylarScore),那么如果score变量等于7,则输出7。我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

你不能在Python中拥有kaiylar - 30/04/1984变量。 Python变量命名规则在PEP 8中描述(另请参见此相关主题:What is the naming convention in Python for variable and function names?)。

相反,请考虑使用dictionary

data = {}
firstName = input("What's your first name? ")
data[firstName + " - " + DOB] = score

或者,根据最终目标,您可以在单独的键下使用名字,DOB和得分:

{
    "first_name": firstName,
    "date_of_birth": DOB,
    "score": score
}

或者,为了更进一步,您可以使用Personfirst_namedate_of_birth属性来定义score

答案 1 :(得分:-1)

正如其他答案和评论中所讨论的,您应该使用字典。但是如果您认为应该根据Python命名规则创建动态变量,则可以使用exec内置函数,如下所示:

score = 1.2
firstName = input("What's your first name? ")
exec(firstName + "Score" + "= score")

实际上exec函数动态地运行Python语句。 İffirstName变量是“Kaiylar”而score变量是int的“1.2”,然后我们将“KaiylarScore = 1.2”语句传递给此函数。

问候。