首页 > 解决方案 > Python:如何将字符串与等于数字的变量配对

问题描述

如何将字符串与等于数字的变量配对?例如

king = random.randint(150 , 300)

attackred = str(input("who would you like to attack with"))

if (attackred == "king"):

    redking = ("king")

在第 1 行中,我将 king 变量设置为 150-300 之间的整数 在第 2 行中,我问打字员他想攻击谁, king 只是一个例子,第 3 和第 4 行有多个选项,我创建了一个if 语句,因此当用户在第 2 行中键入 ("king") 时,它将与 redking 变量配对,该变量是一个数字,因此我可以稍后在我的代码中使用它。

标签: pythonpython-3.x

解决方案


如果我理解正确,您希望将用户键入的字符串与第 1 行中生成的数字“关联”(即变量 king)

在这种情况下,您可以使用字典。使用类似的东西:

ref_dictionary = {}
king = random.randint(150 , 300)
attackred = str(input("who would you like to attack with"))

ref_dictionary[attackred] = king

if (attackred == "king"):
    redking = ref_dictionary[attackred]

推荐阅读