【问题标题】:Only last iteration of while loop saves只有while循环的最后一次迭代保存
【发布时间】:2014-12-20 02:02:10
【问题描述】:

我有这个代码:

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 新手。

【问题讨论】:

  • 请修正缩进

标签: python while-loop


【解决方案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 行。

【讨论】:

    猜你喜欢
    • 2016-04-23
    • 2015-03-23
    • 1970-01-01
    • 2012-05-28
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    • 2018-05-14
    • 2021-05-11
    相关资源
    最近更新 更多