为了账号安全,请及时绑定邮箱和手机立即绑定

Python高效编程(二)

实际编程和面试都会遇到的典型问题。

图片来源于网络

如何实现可迭代对象和迭代器对象?

# 可迭代对象
l = [1,2,3,4]
s = 'abcde'

# 迭代器对象
t = iter(l)

import requests
from collections import Iterator,Iterable

#实现一个迭代器对象WeatherIterator,__next__方法每次返回一个城市气温
class WeatherIterator(Iterator):
    def __init__(self,cities):
        self.cities = cities
        self.index = 0
        
    def getWeather(city):
        r = requests.get(u'http://wthrcdn.etouch.cn/weather_mini?city=' + city)
        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 getWeather(city)

# 实现一个可迭代对象WeatherIterable,__iter__方法返回一个迭代器对象
class WeatherIterable(Iterable):
    def __init__(self,cities):
        self.cities = cities
        
    def __iter__(self):
        return WeatherIterator(self.cities)
    
#[u'漠河',u'海南',u'乌鲁木齐',u'上海']
for x in WeatherIterable([u'漠河',u'海南',u'乌鲁木齐',u'上海']):
    print(x)

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

生成器

生成器既实现了__iter__接口,又实现了__next__接口,并且__iter__返回的就是生成器本身。

# 给定一个可迭代对象的类,它能迭代出给定范围内的所有素数

class PrimeNumbers():
    def __init__(self,start,end):
        self.start = start
        self.end = end
        
    def isPrimeNum(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.isPrimeNum(k):
                yield k

                
for x in PrimeNumbers(1,100):
    print(x)

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

# 实现一个连续浮点数发生器FloatRange(start,end,step)

# l = [1,2,3,4,5]

# for x in reversed(l):
#     print(x)

class FloatRange():
    def __init__(self,start,end,step=0.1):
        self.start = start
        self.end = end
        self.step = step
    
    def __iter__(self):
        t = self.start
        while t < self.end:
            yield t
            t += self.step
            
    def __reversed__(self):
        t = self.end - self.step
        while t >= self.start:
            yield t
            t -= self.step


for x in reversed(FloatRange(1.0,5.5,0.5)):
    print(x)

如何对迭代器做切片操作?

# 有一个文本文件,我们想获取某范围内的内容 eg:100-300lines

import this

f = open('test','w')
f.write(this.s)
f.close()

from itertools import islice

f = open('test','r')
for x in islice(f,3,5):
    print(x)

如何在一个for语句中迭代多个可迭代对象?

from random import randint

# 每个学生有三门成绩(并行)
chese_grade = [randint(60,100) for _ in range(50)]
english_grade = [randint(60,100) for _ in range(50)]
math_grade = [randint(60,100) for _ in range(50)]

for c,e,m in zip(chese_grade,english_grade,math_grade):
    print('总分:%3d 语文:%3d 英语:%3d 数学:%3d'%(c+e+m,c,e,m))

# 有四个班,一次英语考试的成绩存储在四个列表里,统计90以上的人数(串行)
from itertools import chain

chain([1,2,3,4],['a','b','c'])

english_grade1 = [randint(60,100) for _ in range(45)]
english_grade2 = [randint(60,100) for _ in range(53)]
english_grade3 = [randint(60,100) for _ in range(49)]
english_grade4 = [randint(60,100) for _ in range(35)]

count = 0

for x in chain(english_grade1,english_grade2,english_grade3,english_grade4):
    if x >= 90:
        count += 1

print(count)
点击查看更多内容
2人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消