2013-12-11 23 views
0

我在我正在工作的項目中有一段代碼,其中包括一個for循環。然而,在我看來,for循環沒有循環遍歷我告訴它的整個列表。這是我的代碼,以我爲例做了一個清單:For循環Python停止之前,我想它

ans_list = ['9', '4', ',', '7', '3'] 
ans_list_final = [] 
temp_str = "" #This string holds each number before it gets appended onto ans_list_final 

for i in ans_list: 
    if i != ",": 
     temp_str += str(i) 
    else: 
     ans_list_final.append(int(temp_str)) 
     temp_str = "" #Reset for a new number 

print ans_list_final 

我想這個打印[94,73],但它只能打印[94],顯然得到的逗號卡莫名其妙。我不知道爲什麼,因爲for循環應該貫穿整個ans_list。我在這裏錯過了什麼?

+0

如果'i ==「,」'只會發生一次,它只會追加到ans_list_final。 – RemcoGerlich

+0

作爲旁註,這是更pythonic:'map(int,''.join(ans_list).split(','))' –

回答

0

當循環結束,temp_str73但環越過它執行

ans_list_final.append(int(temp_str)) 

可以循環後print temp_str確認在此之前。所以,你必須有這條線在循環的末尾,以確保我們收集剩餘的項目在temp_str

if temp_str: 
    ans_list_final.append(int(temp_str)) 
0
[int(n) for n in ''.join(ans_list).split(',')] 

我是串methond和列表comprehesion的一大樂趣。所以這是我喜歡的版本。