我要完成的工作:我想从darksky API获取 future 7天的最高温度,最低温度和时间列表。当我尝试打印变量时,我一直收到此消息(TypeError:“float”对象不可下标)。最终结果是使用pandas将此数据导入到Dataframe中,代码显然没有完成。
同样,答案可能是显而易见的(在这里newb)。谢谢大家的帮助!
import pandas as pd
import requests
import json
key = '(my dark sky api key)'
url = 'https://api.darksky.net/forecast/%s/43.0481221,-76.147424' % (key)
response = requests.get(url)
weather_data = response.json()
time = weather_data['currently']['apparentTemperature']['daily']['data'][0:8]['time']
temperature_min = weather_data['currently']['apparentTemperature']['daily']['data'][0:8]['apparentTemperatureMin']
temperature_max = weather_data['currently']['apparentTemperature']['daily']['data'][0:8]['apparentTemperatureMax']
print(temperature_min)
TypeError: 'float' object is not subscriptable
最佳答案
显然问题出在您试图用来检索所需数据的数据结构和索引。weather_data['currently']
将给您字典对象:
{'apparentTemperature': 57.44,
'cloudCover': 0.29,
'dewPoint': 33.07,
'humidity': 0.4,
'icon': 'partly-cloudy-day',
'nearestStormBearing': 242,
'nearestStormDistance': 436,
'ozone': 358.37,
'precipIntensity': 0,
'precipProbability': 0,
'pressure': 1028.68,
'summary': 'Partly Cloudy',
'temperature': 57.44,
'time': 1492546503,
'visibility': 10,
'windBearing': 4,
'windSpeed': 2.16}
weather_data['currently']['apparentTemperature']
给出float
号57.44
。当您进一步尝试下标时,会出现错误,因为浮点数不可下标。我建议研究更多的weather_data
数据结构,并选择正确的索引以提供所需的数据。尝试这个:
time = [weather_data['daily']['data'][k]['time'] for k in range(0,8)]
temperature_min = [weather_data['daily']['data'][k]['apparentTemperatureMin'] for k in range(0,8)]
temperature_max = [weather_data['daily']['data'][k]['apparentTemperatureMax'] for k in range(0,8)]
在这里,列表推导用于检索8天的数据。如果您想接收某些特定日期,请使用特定日期的
list
(例如[2,5,6])而不是range(0,8)
关于python - 尝试从Darksky API获取值列表时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43481323/