[英]For loop in Python stopping before I want it to
I have a section of code in a project I'm working on which includes a for loop. 我正在处理的项目中有一段代码,其中包括for循环。 It seems to me, however, that the for loop isn't cycling through the entire list that I tell it to.
但是在我看来,for循环并没有遍历我告诉它的整个列表。 This is the code I have, with a list I made for an example:
这是我的代码,并带有一个示例列表:
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
I want this to print [94, 73], but it only prints [94], apparently getting stuck at the comma somehow. 我要打印[94,73],但只打印[94],显然以某种方式卡在逗号上。 I'm not sure why, as the for loop should go through the entire ans_list.
我不确定为什么,因为for循环应该遍历整个ans_list。 What am I missing here?
我在这里想念什么?
When the loop ends, temp_str
has 73
but the loop gets over before it executes 循环结束时,
temp_str
有73
但是循环在执行之前结束
ans_list_final.append(int(temp_str))
You can confirm this by print temp_str
after the loop. 您可以在循环后通过
print temp_str
来确认这一点。 So, you have to have this line at the end of the loop, to make sure that we gather the remaining item in temp_str
因此,您必须在循环的末尾有此行,以确保我们将剩余的项目收集在
temp_str
if temp_str:
ans_list_final.append(int(temp_str))
[int(n) for n in ''.join(ans_list).split(',')]
i am a big fun of string methond and list comprehesion. 我很喜欢字符串methond和列表解释。 So this is the version i prefer.
所以这是我喜欢的版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.