# Python高效编程（二）

2019.04.04 15:15 443浏览

### 如何实现可迭代对象和迭代器对象？

``````# 可迭代对象
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)
``````

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

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

def __init__(self,start,end):
self.start = start
self.end = end

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):
yield k

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)]

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

if x >= 90:
count += 1

print(count)
``````

2人点赞

• 2
• 评论
• 收藏
• 共同学习，写下你的评论

0/150