可迭代对象与迭代器

可迭代对象与迭代器的区别:

  1. 可迭代对象包括迭代器
  2. 可迭代对象必须实现_iter_方法,迭代器必须实现_iter_方法和next方法
  3. 如果一个对象拥有_iter_方法,该对象为可迭代对象,如果一个对象拥有next方法,该对象为迭代器 可迭代对象包括:迭代器、序列(列表、元组、字符串等)、字典

获得城市天气:

  1. 实现一个迭代器对象WeatherIterator,next()方法,每次返回一个城市气温。
  2. 实现一个可迭代对象WeatherIterable,__iter__方法返回一个迭代对象。
import requests

#迭代器
class weatherIterlator(object):
    def __init__(self, cities):
        self.cities = cities
        self.index = 0
    def getWeather(self, city):
        r = requests.get(u'http://http://www.weather.com.cn/'+city)  #对某一固定方式进行get请求
        data = r.json()['data']['forecast'][0]
        return '%s:%s,%s'%(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():
    def __init__(self, cities):
        self.cities = cities
    def __iter__(self):            #可迭代对象标志
        return weatherIterlator(self.cities)
#实例化
for x in weatherIterable([u'北京', u'上海', u'广州', u'西安', u'深圳']):
    print(x)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值