首先,爲標題道歉,我想不出一個更好的。我想要做的是能夠減少我的代碼中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 –