2017-04-19 187 views
1

Python noob在這裏如此原諒我,如果我有一個簡單的問題。我想將變量名設置爲我通過for循環傳遞的任何值。將變量連接變量

roles = ["A" , "B" , "C"] 
for role in roles: 
    print (role) 
    "outPutFor"+role = function_that_gives_outputforRole(role) 

所以我想我的變量讀outPutForAoutPutForBoutPutForC

但我提示以下錯誤:

"outPutFor"+role = function_that_gives_outputforRole(role) 
     ^
SyntaxError: can't assign to operator 

缺少什麼我在這裏?

+0

該錯誤表明問題。請參閱http://stackoverflow.com/questions/8956825/syntax-error-cant-assign-to-operator。 – sgrg

+2

你可能不想這樣做,大概只有'outPutFor'字典和outPutFor [「A」]''''會比'outPutForA'更好。這樣你也可以輕鬆地遍歷所有的可能性。 – 098799

+1

你不能'計算'變量的*名稱*。你只能計算變量的'內容'。這就是爲什麼你應該推廣循環中的邏輯。 'outPutForA'是第一次迭代中的'輸出'(當'role'設置爲''A''時)。因此,你可能想要設置'output ='outPutFor'+ role'或'output ='outPutFor'+ function_that_gives_outputforRole(role)'。 – mhoff

回答

1

您無法創建一個動態命名的變量。但是你可以使用一個python dict

roles = ["A" , "B" , "C"] 
outputs = {} 
for role in roles: 
    print (role) 
    outputs["outPutFor"+role] = function_that_gives_outputforRole(role) 

或從「角色」列表作爲鍵的元素創建dict。像

roles = ["A" , "B" , "C"] 
outPutFor = {} 
for role in roles: 
    print (role) 
    outPutFor[role] = function_that_gives_outputforRole(role) 
    print(outPutFor[role]) 
+1

爲什麼要使用'outputs.update({key:value})'而不是普通的'outputs [key] = value'? – khelwood

+1

@khelwood感謝您的評論。是的,'outputs [key] = value'是更好的解決方案。我編輯了我的帖子。 – kvorobiev

1

如果你正在尋找一種方式來存儲這些函數的每次迭代的output,您可以創建一個名爲listresults,例如,和for each role in roles,您可以insert/assignfunction_that_gives_outputforRole輸出入results列表。

例子:

roles = ["A" , "B" , "C"] 
results = [] 
for i, role in enumerate(roles): 
    results[i] = function_that_gives_outputforRole(role) 

在這個例子中,你可以爲每個角色類似這樣的訪問產值:

results[0] = function_that_gives_outputforRole("A") 
results[1] = function_that_gives_outputforRole("B") 
results[2] = function_that_gives_outputforRole("C") 

你也可以使用一個dict結構來存儲每個輸出,如kvorobiev's answer中所述。

如果你願意,你可以將zip()這兩個列表合併成一個列表來鞏固輸入/輸出值。