![](/img/trans.png)
[英]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.