简体   繁体   中英

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. It seems to me, however, that the for loop isn't cycling through the entire list that I tell it to. 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. I'm not sure why, as the for loop should go through the entire ans_list. What am I missing here?

When the loop ends, temp_str has 73 but the loop gets over before it executes

ans_list_final.append(int(temp_str))

You can confirm this by print temp_str after the loop. 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

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. So this is the version i prefer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM