程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2023-05(1)

2023-06(3)

8.python3实用编程技巧进阶(三)

发布于2019-08-17 14:46     阅读(951)     评论(0)     点赞(1)     收藏(2)


3.1.如何实现可迭代对象和迭代器对象

复制代码
#3.1 如何实现可迭代对象和迭代器对象

import requests
from collections.abc import Iterable,Iterator

class WeatherIterator(Iterator):
    def __init__(self,cities):
        self.cities = cities
        #从列表中迭代一个city,index就+1
        self.index = 0

    def __next__(self):
        #如果所有的城市都迭代完了,就抛出异常
        if self.index == len(self.cities):
            raise StopIteration
        #当前迭代的city
        city = self.cities[self.index]
        #迭代完当前city,index就+1
        self.index += 1
        return self.get_weather(city)

    def get_weather(self,city):
        url = 'http://wthrcdn.etouch.cn/weather_mini?city=' + city
        r = requests.get(url)
        #获取当天的天气信息
        data = r.json()['data']['forecast'][0]
        #返回城市名字、最高和最低气温
        return city, data['high'], data['low']


class WeatherIterable(Iterable):
    def __init__(self,cities):
        self.cities = cities

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


def show(w):
    for x in w:
        print(x)

weather = WeatherIterable(['北京','上海','广州','深圳','东莞'])
show(weather)
复制代码

结果

3.2如何使用生成器函数实现可迭代对象

复制代码
#3.2如何使用生成器函数实现可迭代对象

from collections.abc import Iterable

class PrimeNumbers(Iterable):
    def __init__(self,a,b):
        self.a = a
        self.b = b

    def __iter__(self):
        for k in range(self.a,self.b):
            if self.is_prime(k):
                yield k

    def is_prime(self,k):
        return False if k < 2 else all(map(lambda x : k % x, range(2, k)))

#打印1到30直接的素数
pn = PrimeNumbers(1, 30)
for n in pn:
    print(n)
复制代码

3.3.如何进行反向迭代以及如何实现反向迭代

反向迭代

复制代码
In [75]: l = [1,2,3,4,5]

In [76]: for x in l:
    ...:     print(x)
    ...:
1
2
3
4
5

In [77]: for x in reversed(l):
    ...:     print(x)
    ...:
5
4
3
2
1

复制代码

要想实现反向迭代必须实现__reversed__方法

复制代码
#3.3.如何进行反向迭代以及如何实现反向迭代

class IntRange:
    def __init__(self,a,b,step):
        self.a = a
        self.b = b
        self.step = step

    def __iter__(self):
        t = self.a
        while t <= self.b:
            yield t
            t += self.step
    
    def __reversed__(self):
        t = self.b
        while t >= self.a:
            yield t
            t -= self.step

fr = IntRange(1, 10, 2)

for x in fr:
    print(x)

print('=' * 30)

#反向迭代
for y in reversed(fr):
    print(y)
复制代码

 



所属网站分类: 技术文章 > 博客

作者:集天地之正气

链接:https://www.pythonheidong.com/blog/article/47434/bfdd649ea4fb62ac77c7/

来源:python黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

1 0
收藏该文
已收藏

评论内容:(最多支持255个字符)