Only last iteration of while loop saves

前端 未结 1 891
无人及你
无人及你 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

    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)
提交回复
热议问题