2017-09-21 50 views
0

我試圖做一個(一個想法)而不是簡單的任務與Python但似乎無法做到或找到一種方法來做到這一點。我試圖有一個for循環,其中我的變量設置爲另一個自定義數字的變量。這是一個有點難以解釋,但我的代碼將更好地解釋它:Python - 使用for循環與自定義變量命名

aha_aha1 = "1" 
aha_aha2 = "wouh" 
aha_aha3 = "yes !" 
test = "my man !" 

for i in range (0, 4): 
    if aha_aha{i} = "yes !": 
    test[i] == aha_aha{i}.format(i) 

我想test[i]aha_aha[i]只有當某些條件得到滿足,但我上面的代碼顯然是行不通的。任何幫助?

+0

你不能命名變量'aha_aha1,aha_aha2,..',然後根據名稱中的數字(即,'aha_aha {i}'在Python中不存在)選擇它們。你必須做一個「列表」,並通過索引 – GPhilo

+0

來訪問它們哦,這是一個恥辱。謝謝,會做到這一點! – CommYov

+1

使用字典 –

回答

1

如果你真的想那些「aha_x的:

d = {"aha_aha1" : "1", "aha_aha2" : "wouh", "aha_aha3" : "yes !"} 
test = "my man !" 

for i in range (0, 4): 
    temp = "aha_aha"+str(i) 
    if d.get(temp) == "yes !": 
    #Do something 
+0

我從外部來源獲取我的變量,並且都有這樣的東西something_1,something_2等... – CommYov

+0

@CommYov如果您知道變量將以某種已知的固定格式到達,應該有幫助 – ketan

0

其實,我不明白你在做什麼,但是從這裏至少開始:

aha_aha_list = ["1", "wouh", "yes !"] 
test = "my man !" 

for aha_aha in aha_aha_list: 
    if aha_aha is "yes !": 
     test = aha_aha 

print(test) 

輸出:

yes ! 
0

do you want that?in python str type is unable to change,so you should chage str to list,and then chat list to str. 
 
d = {'aha_aha1': '1', 'aha_aha2': 'wouh', 'aha_aha3': 'yes !'} 
 
test = "my man !" 
 
for i in range(0, 4): 
 
    if d.get("aha_aha{i}".format(i=i),None) == "yes !": 
 
     test = list(test) 
 
     test[i] = d.get("aha_aha{i}".format(i=i)) 
 
     test = ''.join(test) 
 
     
 
     
 
    print(test) #my yes !an !