我正在处理的项目中有一段代码,其中包含一个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。我在这里缺少什么?
答案 0 :(得分:0)
当循环结束时,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))
答案 1 :(得分:0)
[int(n) for n in ''.join(ans_list).split(',')]
我是字符串方法和列表理解的忠实粉丝。所以这是我喜欢的版本。