Only last iteration of while loop saves

前端 未结 1 890
无人及你
无人及你 2021-01-22 12:57

I have this code:

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


        
相关标签:
1条回答
  • 2021-01-22 13:16

    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.

    0 讨论(0)
提交回复
热议问题