首先,为标题道歉,我想不出一个更好的。我想要做的是能够减少我的代码中if语句的数量。 这里是我的代码:Python 3.6 - 写入随机变量
if var is "forwardThrustButton":
global forwardThrustButton
forwardThrustButton = res
elif var is "backThrustButton":
global backThrustButton
backThrustButton = res
elif var is "leftRotateButton":
global leftRotateButton
leftRotateButton = res
elif var is "rightRotateButton":
global rightRotateButton
rightRotateButton = res
elif var is "basicShootButton":
global basicShootButton
basicShootButton = res
elif var is "specialShootButton":
global specialShootButton
specialShootButton = res
elif var is "bombShootButton":
global bombShootButton
bombShootButton = res
正如你可以看到我有很多的if语句在这里,用我所投入的函数的字符串,并检查,看看该字符串是什么。此代码有效。我想要做的是能够将一个变量的名称传递给函数,并且只是说var = res
。提前致谢。
请勿使用动态变量,请使用字典。 –
你能解释一下为什么*你需要一个单独的变量取决于另一个变量?这种方法导致的问题是,您永远不知道在某个时间点存在哪些变量。正如@ juanpa.arrivillaga所说:使用字典。看看这里:https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables –
比较字符串与'is'是一个坏主意:https:// stackoverflow.com/questions/1504717/why-does-comparing-strings-in-python-using-either-or-is-sometimes-produce –