我有以下代码:
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新手。
最佳答案
您的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
行。关于python - 仅while循环的最后一次迭代保存,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27571206/