Python - 如何为 eval 赋值

Python - How can I assign a value to eval

如何动态传递变量名?我的观点是,如果用户的输入是 'c',那么 counterc 应该加注 1.

这是我目前的情况。

counterc = 0
countern = 0
counterx = 0
letter = input()

if letter in ['c','n','x']:
  counter${letter} += 1 # does not work
  eval('counter' + letter + '=' + 1) # tried with this one too, but still does not work

locals 内置函数提供了局部变量的 (variable_name => variable_value) 字典。而且,这本词典不是只读的。
然后 locals()[f"counter{letter}"] += 1 应该完成这项工作。
如果您使用的是比 3.6 更旧的 python 版本,请改用 locals()[f"counter{}".format(letter)] += 1

counterc = 0
countern = 0
counterx = 0
letter = input()

if letter in ['c','n','x']:
    globals()['counter{}'.format(letter)] += 1
    print(globals()['counter{}'.format(letter)])

稍后谢谢我 如果你使用的是 python2 输入 'c' 你在 py3 上,只需键入不带引号的 c。

eval方法用于return一个值,不用于执行字符串命令,只接受一行命令

要执行字符串命令,需要exec方法,这里是正确的代码

counterc = 0
countern = 0
counterx = 0
letter = input()

if letter in ['c','n','x']:
  exec('counter' + letter + '=' + 1)