[英]interrupting a loop in python without stopping a function whenever I want
[英]For loop in Python stopping before I want it to
我正在處理的項目中有一段代碼,其中包括for循環。 但是在我看來,for循環並沒有遍歷我告訴它的整個列表。 這是我的代碼,並帶有一個示例列表:
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。 我在這里想念什么?
循環結束時, temp_str
有73
但是循環在執行之前結束
ans_list_final.append(int(temp_str))
您可以在循環后通過print temp_str
來確認這一點。 因此,您必須在循環的末尾有此行,以確保我們將剩余的項目收集在temp_str
if temp_str:
ans_list_final.append(int(temp_str))
[int(n) for n in ''.join(ans_list).split(',')]
我很喜歡字符串methond和列表解釋。 所以這是我喜歡的版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.