迭代
迭代:通过 for 循环来遍历这个 list 或 tuple
def iterator(): for ch in 'this is a wonderful world': print(ch, end=' ') print('\n') nums = [1, 2, 3, 4, 5] for num in nums: print(num, end='') print('\n') dicts = {'name': 'jim', 'age': 24, 'sex': '男'} for key in dicts: print(key, end=' ') print('\n') for value in dicts.values(): print(value, end='') print('\n') for (x, y) in [(1, 'a'), (2, 'b'), (3, 'c')]: print(x, y)
迭代器有两个基本的方法:iter() 和 next(),且字符串,列表或元组对象都可用于创建迭代器,迭代器对象可以使用常规 for 语句进行遍历,也可以使用 next() 函数来遍历。
nums = [1, 2, 3, 4, 5] iterNums = iter(nums) while True: try: print(next(iterNums), end=' ') except StopIteration: break
实现可迭代对象和迭代器对象
需求:从网络抓取各个城市气温信息,并依次显示:
北京:15~20
天津:17~22
长春:12~18
解决方案:
Step1:实现一个迭代器对象WeatherIterator,用__next__(方法每次返回一个城市气温
Step2:实现一个可迭代对象WeatherIterable,用__iter__()方法返回一个迭代器对象
from collections.abc import Iterable, Iterator import requests class WeatherIterator(Iterator): def __init__(self, cities): self.cities = cities self.index = 0 def getWeather(self, city): result = requests.get(u'http://wthrcdn.etouch.cn/weather_mini?city=' + city) data = result.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(Iterable): def __init__(self, cities): self.cities = cities def __iter__(self): return WeatherIterator(self.cities) if __name__ == '__main__': for x in WeatherIterable([u'北京', u'上海', u'广州', u'郑州']): print(x)
生成器迭代对象
class PrimeNumber: def __init__(self, start, end): self.start = start self.end = end def isPrimeNumber(self, number): if number < 2: return False for x in range(2, number): if number % x == 0: return False return True def __iter__(self): for x in range(self.start, self.end): if self.isPrimeNumber(x): yield x if __name__ == '__main__': for x in PrimeNumber(1, 100): print(x)
一个班级语文数据英语的总成绩
def total_grade(): chinese = [randint(60, 100) for _ in range(40)] math = [randint(60, 100) for _ in range(40)] english = [randint(60, 100) for _ in range(40)] total = [] for (ch, m, eng) in zip(chinese, math, english): total.append(ch + m + eng) print(total)
三个班大于90分的成绩
def total_grade(): class1 = [randint(60, 100) for _ in range(40)] class2 = [randint(60, 100) for _ in range(40)] class3 = [randint(60, 100) for _ in range(40)] for x in chain(class1, class2, class3): if x > 90: print(x)
立志如山 静心求实
浙公网安备 33010602011771号