首页 > 解决方案 > 如何将 for 循环中的每个迭代分配给数据库存储的变量

问题描述

我正在尝试从 API 收集天气数据,然后将该数据存储在数据库中以供以后使用。

我已经能够访问数据并使用 for 循环将其打印出来,但我想将该 for 循环的每次迭代分配给一个变量,以存储在数据库中的不同位置。

我怎么能这样做?

我当前的代码如下:

#!/usr/bin/python3

from urllib.request import urlopen
import json

apikey="redacted"
# Latitude & longitude
lati="-26.20227"
longi="28.04363"

# Add units=si to get it in sensible ISO units
url="https://api.forecast.io/forecast/"+apikey+"/"+lati+","+longi+"?units=si"

meteo=urlopen(url).read()
meteo = meteo.decode('utf-8')
weather = json.loads(meteo)

cTemp = (weather['currently']['temperature'])
cSum = (weather['currently']['summary'])
cRain1 =  (weather['currently']['precipProbability'])
cRain2 = cRain1*100
daily = (weather['daily']['summary'])

print (cTemp)
print (cSum)
print (cRain2)
print (daily)

#Everthing above this line works as expected, I am focusing on the below code

dailyTHigh = (weather['daily']['data'])

for i in dailyTHigh:
        print (i['temperatureHigh'])

给我以下输出:

12.76
Clear
0
No precipitation throughout the week, with high temperatures rising to 24°C on Friday.
22.71
22.01
22.82
23.13
23.87
23.71
23.95
22.94

我将如何将 8 个高温中的每一个分配给不同的变量?

即,var1 = 22.71 var2 = 22.01 等

提前致谢,

标签: pythondatabasefor-loopvariables

解决方案


IMO 您需要某种动态长度数据结构,您可以将数据附加到for循环中,然后使用index.

因此,您可以创建 alist然后将forlop 的所有值附加到其中,如下所示:

list = []
for i in dailyTHigh:
        list.append(i['temperatureHigh'])

现在您将能够访问list 如下所示的值:

for i in range(0,len(x)):
    print x[i]

上述方法很好,因为您不需要知道需要插入的项目数量,因为您可能需要相等数量的变量来分配值。您也可以轻松访问这些值。


推荐阅读