python - 如何将 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 等
提前致谢,
解决方案
IMO 您需要某种动态长度数据结构,您可以将数据附加到for
循环中,然后使用index
.
因此,您可以创建 alist
然后将for
lop 的所有值附加到其中,如下所示:
list = []
for i in dailyTHigh:
list.append(i['temperatureHigh'])
现在您将能够访问list
如下所示的值:
for i in range(0,len(x)):
print x[i]
上述方法很好,因为您不需要知道需要插入的项目数量,因为您可能需要相等数量的变量来分配值。您也可以轻松访问这些值。
推荐阅读
- amazon - 特定卖家 ID 的亚马逊添加到购物车产品链接
- matlab - 使用while从matlab中的列接收数据
- snowflake-cloud-data-platform - Snowflake 中的 Match_Recognize 没有返回我认为它应该返回的内容
- flutter - 带有缓存网络图像的 SliverPersistentHeader 会导致每次滚动页面时重新加载图像
- r - 用于删除列中除某个字符串之外的所有内容的 R 函数
- matlab - 如何在 Matlab GUI 中删除 UITable 数据
- python - 执行存储过程并在 qtableview 中检索结果
- c - 为什么对数组大小使用 const int SIZE = 5 仍然会导致错误:可变大小的对象可能未初始化?
- android - 如何在 Android 上单击按钮创建 OpenGL ES 资源
- api - 超过 60 个结果 google place api