【问题标题】:How to slice weather data from a dictionary and re-write?如何从字典中切片天气数据并重写?
【发布时间】:2019-12-14 21:36:00
【问题描述】:

我从weatherbit-api 获得了一些数据。而且我真的需要帮助来分割数据。

以下是我的代码:

from weatherbit.api import Api
api_key = "******************"
api = Api(api_key)

Location = "Tokyo"
Day_of_Forecast = '3'
forecast = api.get_forecast(days = Day_of_Forecast, city= Location)
forecast_list = forecast.get_series(['temp', 'max_temp', 'min_temp', 'weather'])
print(forecast_list)

它返回如下:

[{'temp': 33, 'max_temp': 36.5, 'min_temp': 29.5, 'weather': {'icon': 'c03d', 'code': 803, 'description': 'Broken clouds'}, 'datetime': datetime.datetime(2019, 8, 7, 0, 0)},
{'temp': 31.3, 'max_temp': 35.3, 'min_temp': 28.8, 'weather': {'icon': 'c04d', 'code': 804, 'description': 'Overcast clouds'}, 'datetime': datetime.datetime(2019, 8, 8, 0, 0)},
{'temp': 30.7, 'max_temp': 34.4, 'min_temp': 28.4, 'weather': {'icon': 'c03d', 'code': 803, 'description': 'Broken clouds'}, 'datetime': datetime.datetime(2019, 8, 9, 0, 0)}]

所以对于上面的列表,我怎样才能切开它并重写它以返回这样的结果,例如:

The weather forecast for Tokyo is:
On 7th of August 2019, the weather forecast is Broken clouds. The temperature will be 33 celsius degree, the maximum temperature will be 36.5 celsius degree and minimum temperature will be 29.5 degree.
On 8th of August , the weather forecast is Overcast clouds. The temperature will be 31.3 celsius degree, the maximum temperature will be 35.3 celsius degree and minimum temperature will be 28.8 degree.
On 9th of August , the weather forecast is Broken clouds. The temperature will be 30.7 celsius degree, the maximum temperature will be 34.4 celsius degree and minimum temperature will be 28.4 degree.

很抱歉这个菜鸟问题,但这是我练习的一部分,我已经为此苦苦挣扎了好几天。 我非常感谢您的帮助。太感谢了。 随意复制列表或任何内容。

【问题讨论】:

    标签: python-3.x list datetime dictionary


    【解决方案1】:
    def better_forecast_list(forecast_list):
        better_list = []
        for forecast in forecast_list:
            better_list.append(
                f'''Today is {forecast['datetime']: %d %B %Y} \
                 weather is {forecast['weather']['description']} \
                 temp will be {forecast['temp']} 
                ''')
        return better_list
    

    顺便说一句,我使用了f 字符串。它仅在 python 3.7 以上可用

    【讨论】:

    • 天啊!!太感谢了。根据您的功能,我将列表切片并成功重写。非常感谢你。!!!!
    猜你喜欢
    • 2013-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-28
    • 1970-01-01
    • 2015-05-26
    • 2017-01-28
    相关资源
    最近更新 更多