如何通过管道动态传递变量名?我的观点是,如果用户的输入是'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
eval
方法用于返回值,不用于执行string命令,只接受一行命令要执行string命令,需要
exec
方法,下面是正确的代码locals
内置函数提供局部变量的(variable\u name=>;variable\u value)字典。此外,本词典不是只读的。那么
locals()[f"counter{letter}"] += 1
就应该做这项工作了。如果您使用的是比3.6旧的python版本,请改用
locals()[f"counter{}".format(letter)] += 1
。你知道吗以后谢谢我 如果你用的是python2,那么输入'c'就在py3上,只需输入c而不加引号。你知道吗
相关问题 更多 >
编程相关推荐