Python - 怎么分配值

2024-09-28 22:53:20 发布

您现在位置:Python中文网/ 问答频道 /正文

如何通过管道动态传递变量名?我的观点是,如果用户的输入是'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

Tags: 用户inputif管道counternot情况动态
3条回答

eval方法用于返回值,不用于执行string命令,只接受一行命令

要执行string命令,需要exec方法,下面是正确的代码

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

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

locals内置函数提供局部变量的(variable\u name=>;variable\u 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而不加引号。你知道吗

相关问题 更多 >