gpt4 book ai didi

python - 如何将 for 循环中的每个迭代分配给数据库存储的变量

转载 作者:搜寻专家 更新时间:2023-10-30 22:05:43 26 4
gpt4 key购买 nike

我正在尝试从 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.71var2 = 22.01等等

提前致谢

最佳答案

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

因此,您可以创建一个list,然后将for lop 的所有值附加到其中,如下所示:

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

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

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

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

关于python - 如何将 for 循环中的每个迭代分配给数据库存储的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55877915/

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