Python3 practices

理解迭代器和生成器

 

# -*- coding: utf-8 -*-
"""
3-2 迭代器

iterable : 
    可以迭代的对象(比如字符,文件),
    有 __iter__ method 能返回 iterator, 或者有__getitem__ method.相当于容器。

iterator : 
    在迭代中记住状态,
    有 __next__ method:
        能返回下一个值,
        能更新状态指向下一值,
        当完成所有迭代时 raise StopIteration.
    自身 self-iterable (自身有__iter__ method返回self)。
    
Note:
    __next__ method 在python2 为 next method
    The builtin function next() calls that method on the object passed to it.
"""

import requests

from collections import Iterable, Iterator


class WeatherIterator(Iterator):
    def __init__(self, cities):
        self.cities = cities
        self.index = 0
        
    def getweather(self, city):  
        r = requests.get(u'http://wthrcdn.etouch.cn/weather_mini?city=' + city) #unicode
        data = r.json()['data']['forecast'][0]
        return 'low-{1} high-{2},{0}'.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([u'南京',u'苏州',u'扬州']): print(x)  

 

# -*- coding: utf-8 -*-
"""
3-3 生成器 yeild :使用生成器哈数实现可迭代对象
Q:
实现一个可迭代对象的类,它能够迭代出给定范围内的所以质数。
A:
将该类的__iter__ method实现成生成器,每次yield返回一个质数。
"""

class PrimeNumbers:
    def  __init__(self, start, end):
        self.start = start
        self.end = end
        
    def isPrime(self, k):
        if k < 2: return False
        
        for i in range(2,k):
            if k % i == 0: return False
            
        return True
    
    def __iter__(self):
        for k in range(self.start, self.end +1):
            if self.isPrime(k):
                yield k
                
a = PrimeNumbers(10,40)

for x in a: print(x)

 

转载于:https://www.cnblogs.com/JMJM-Li/p/8530886.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值