python - 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 变量配对,该变量是一个数字,因此我可以稍后在我的代码中使用它。
解决方案
如果我理解正确,您希望将用户键入的字符串与第 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]
推荐阅读
- python - 将 pandas 数组的数据类型从 obj 更改为 int
- html - 不同子域的不同社交元预览
- ios - AVCaptureVideoDataOutput 在 iOS 14 中停止传送帧
- c# - 如何在系统路径中找到文件的位置,例如 get-command 或 where?
- perl - Perl 中的 Jenkins 哈希?
- python - 我如何对 docx 生成功能进行单元测试
- python - Akamai Python 登录与耐克
- php - PHP Gmail Api - 删除邮件
- google-apps-script - 为 Google 表格中的每一行自动发送电子邮件
- flutter - 如何从一侧移除高程阴影而不从卡片或材质小部件中移除高程本身?