gpt4 book ai didi

python - 只有 while 循环的最后一次迭代保存

转载 作者:太空宇宙 更新时间:2023-11-04 05:56:21 24 4
gpt4 key购买 nike

我有这个代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com