[Python高效编程] - 获取天气信息并使用迭代for输出

本文介绍了在Python3.6环境下,利用requests和collections库获取天气信息,并通过可迭代对象和迭代器进行信息输出。文章还探讨了代码优化的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

开发环境

  1. Python版本: python3.6
  2. 调试工具:pycharm 2017.1.3
  3. 电脑系统:Windows 10 64位系统
  4. Python库:requests,collections

获取天气信息

import requests


def getWeather(city):
    r = requests.get("http://wthrcdn.etouch.cn/weather_mini?city=" + city)
    data = r.json()['data']['forecast'][0]
    return '{0}: {1}, {2}'.format(city, data['low'], data['high'])


print(getWeather('武汉'))
武汉: 低温 4℃, 高温 15℃

使用可迭代对象和迭代器输出信息

from collections import Iterable, Iterator

import requests


class WeatherIterator(Iterator):
    # 继承可迭代的对象
    def __init__(self, cities):
        self.cities = cities
        self.index = 0

    def getWeather(self, city):
        r = requests.get("http://wthrcdn.etouch.cn/weather_mini?city=" + city)
        data = r.json()['data']['forecast'][0]
        return '{0}: {1}, {2}'.format(city, data['low'], data['high'])

    def __next__(self):
        if self.index == len(self.cities):
            raise StopIteration
        city = self.cities[self.index]
        self.index += 1
        return self.getWeather(city)


class WeatherIterable(Iterable):
    # 继承迭代器
    def __init__(self, cities):
        self.cities = cities

    def __iter__(self):
        return WeatherIterator(self.cities)

for x in WeatherIterable(['北京', '上海', '武汉', '深圳']):
    print(x)


北京: 低温 -4℃, 高温 7℃
上海: 低温 5℃, 高温 13℃
武汉: 低温 4℃, 高温 15℃
深圳: 低温 13℃, 高温 19℃

代码优化

上述的代码还是不够简洁,还可以进一步优化,下面重写代码

import requests

class WeatherOutput:
    """输出天气信息"""
    def __init__(self, cities):
        self.cities = cities
        self.index = 0

    def getWeather(self, city):
        try:
            r = requests.get("http://wthrcdn.etouch.cn/weather_mini?city=" + city)
            data = r.json()['data']['forecast'][0]
            return '{0}: {1}, {2}'.format(city, data['low'], data['high'])
        except:
            print("获取天气信息失败")

    def __iter__(self):
        return self

    def __next__(self):
        if self.index == len(self.cities):
            raise StopIteration
        city = self.cities[self.index]
        self.index += 1
        return self.getWeather(city)

for x in WeatherOutput(['北京', '上海', '武汉', '深圳']):
    print(x)
北京: 低温 -4℃, 高温 7℃
上海: 低温 8℃, 高温 14℃
武汉: 低温 4℃, 高温 17℃
深圳: 低温 15℃, 高温 19℃

如果想知道原理,可以参考这篇博客:

http://blog.youkuaiyun.com/lanhaixuanvv/article/details/78503325

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值