只有while循环的最后一次迭代才会保存

时间:2014-12-19 17:41:43

标签: python while-loop

我有这段代码:

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

输出:

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

这很好但是当我尝试将这些代码切换成较小的变量时它不会让我。例如,pricelist,[0:20]将只输出while循环的最后一次迭代。对不起,我是Python的新手。

1 个答案:

答案 0 :(得分:1)

在循环的每次迭代中都会覆盖您的pricelist变量。您需要将结果存储在某种数据结构中,例如list(而list将与您希望使用的[0:20]切片符号一起使用):

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

现在你可以做到:

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

就像你想要的那样。

我还建议使用for循环,而不是在while循环中手动递增计数器。

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.

如果你这样做,你可以省略最后的i+=1行。

相关问题