Python noob在這裏如此原諒我,如果我有一個簡單的問題。我想將變量名設置爲我通過for循環傳遞的任何值。將變量連接變量
roles = ["A" , "B" , "C"]
for role in roles:
print (role)
"outPutFor"+role = function_that_gives_outputforRole(role)
所以我想我的變量讀outPutForA
,outPutForB
和outPutForC
。
但我提示以下錯誤:
"outPutFor"+role = function_that_gives_outputforRole(role)
^
SyntaxError: can't assign to operator
缺少什麼我在這裏?
該錯誤表明問題。請參閱http://stackoverflow.com/questions/8956825/syntax-error-cant-assign-to-operator。 – sgrg
你可能不想這樣做,大概只有'outPutFor'字典和outPutFor [「A」]''''會比'outPutForA'更好。這樣你也可以輕鬆地遍歷所有的可能性。 – 098799
你不能'計算'變量的*名稱*。你只能計算變量的'內容'。這就是爲什麼你應該推廣循環中的邏輯。 'outPutForA'是第一次迭代中的'輸出'(當'role'設置爲''A''時)。因此,你可能想要設置'output ='outPutFor'+ role'或'output ='outPutFor'+ function_that_gives_outputforRole(role)'。 – mhoff