简体   繁体   English

Python 将输入与变量混合

[英]Python mixing inputs with variables

i have some variables and in an input i need to specify a variable.我有一些变量,在输入中我需要指定一个变量。

for example if an input is "B1 5" then the Integer B1 gets +5.例如,如果输入是“B1 5”,那么 Integer B1 将获得 +5。

I know how to do this the very long way but my application has many Integer variables wich all need to do this.我知道如何做到这一点很长,但我的应用程序有许多 Integer 变量都需要这样做。

sorry for bad english抱歉英语不好

Rather than statically naming your variables in your code, keep them in a dictionary so you can easily address them by name at runtime.与其在代码中静态命名变量,不如将它们保存在字典中,这样您就可以在运行时轻松地按名称寻址它们。

Here's a demo of how this might work:这是如何工作的演示:

from collections import defaultdict
from typing import Dict

vars: Dict[str, int] = defaultdict(int)
while True:
    try:
        var, inc = input("Gimme a variable and an increment: ").split()
        vars[var] += int(inc)
    except:
        break
print(dict(vars))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM