Only last iteration of while loop saves

2020-04-17 03:37发布

问题:

I have this code:

symbolslist = ["100","200","300","400","500","600","700","800","900","1000","1500","2000","3000","4000","5000","7000","10000"]

i=0
while i<len(symbolslist):
     htmltext = urllib.urlopen("http://www.fifacoinszone.com/default/quick/getpricedetail? platform_id=7&coins="+symbolslist[i] +"&cur=GBP")
     data = json.load(htmltext)
     pricelist = data["single_price_just"]
     print pricelist,
     i+=1

This outputs:

4.69 9.32 13.91 18.46 22.96 27.41 31.82 36.18 40.50 44.78 66.83 88.66 132.32 175.55 218.34 304.15 345.86 430.17 3.94 7.83 11.69 15.51 19.29 23.03 26.74 30.40 34.03 37.62 56.15 74.50 111.19 147.52 183.48 255.58 363.30

which is fine but when I try to then chop this code into smaller variables it doesn't let me. For example,pricelist,[0:20] will just output the last iteration of the while loop. Sorry I am new to Python.

回答1:

Your pricelist variable is being overwritten on each iteration of the loop. You need to store your result in a data structure of some sort, such as a list (and a list will work with the [0:20] slice notation you wish to use):

symbolslist = ["100","200","300","400","500","600","700","800","900","1000","1500","2000","3000","4000","5000","7000","10000"]
pricelist = [] #empty list

i=0
while i<len(symbolslist):
    htmltext = urllib.urlopen("http://www.fifacoinszone.com/default/quick/getpricedetail?platform_id=7&coins="+symbolslist[i] +"&cur=GBP")
    data = json.load(htmltext)
    pricelist.append(data["single_price_just"]) #appends your result to end of the list
    print pricelist[i] #prints the most recently added member of pricelist
    i+=1

Now you can do:

pricelist[0:20] #returns members 0 to 19 of pricelist

Just like you wanted.

I also suggest using a for loop instead of manually incrementing your counter in a while loop.

Python 2:

for i in xrange(len(symbolslist)):

Python 3:

for i in range(len(symbolslist)):
#xrange will also work in Python 3, but it's just there to 
#provide backward compatibility.

If you do it this way you can omit the i+=1 line at the end.