国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python中對象迭代與反迭代的技巧總結

2019-11-25 16:33:45
字體:
來源:轉載
供稿:網友

一、如何實現可迭代對象和迭代器對象?

實際案例

某軟件要求從網絡抓取各個城市氣味信息,并其次顯示:

北京: 15 ~ 20 天津: 17 ~ 22 長春: 12 ~ 18 ......

如果一次抓取所有城市天氣再顯示,顯示第一個城市氣溫時,有很高的延時,并且浪費存儲空間,我們期望以用時訪問的策略,并且把所有城市氣溫封裝到一個對象里,可用for語句進行迭代,如何解決?

解決方案

實現一個迭代器對象Weatherlterator,next方法每次返回一個城市氣溫,實現一個可迭代對象Weatherlterable,――――iter__方法返回一個迭代器對象

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('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 self.getWeather(city) # 可迭代對象 class WeatherIterable(Iterable): def __init__(self, cities): self.cities = cities def __iter__(self): return WeatherIterator(self.cities) for x in WeatherIterable(['北京', '上海', '廣州', '深圳']): print(x)

執行結果如下:

C:/Python/Python35/python.exe E:/python-intensive-training/s2.py 北京:低溫 21℃ , 高溫 30℃ 上海:低溫 23℃ , 高溫 26℃ 廣州:低溫 26℃ , 高溫 34℃ 深圳:低溫 27℃ , 高溫 33℃ Process finished with exit code 0

二、如何使用生成器函數實現可迭代對象?

實際案例

實現一個可迭代對象的類,它能迭代出給定范圍內所有素數:

python pn = PrimeNumbers(1, 30) for k in pn: print(k) `` 輸出結果text2 3 5 7 11 13 17 19 23 29“`

解決方案

-將該類的__iter__方法實現生成器函數,每次yield返回一個素數

class PrimeNumbers: def __init__(self, start, stop): self.start = start self.stop = stop 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.stop + 1): if self.isPrimeNum(k): yield k for x in PrimeNumbers(1, 20): print(x)

運行結果

C:/Python/Python35/python.exe E:/python-intensive-training/s3.py 2 3 5 7 11 13 17 19 Process finished with exit code 0

三、如何進行反向迭代以及如何實現反向迭代?

實際案例

實現一個連續浮點數生成器FloatRange(和rrange類似),根據給定范圍(start, stop)和步進值(step)產生一些列連續浮點數,如迭代FloatRange(3.0,4.0,0.2)可產生序列:

正向:3.0 > 3.2 > 3.4 > 3.6 > 3.8 > 4.0 反向:4.0 > 3.8 > 3.6 > 3.4 > 3.2 > 3.0

解決方案

實現反向迭代協議的__reversed__方法,它返回一個反向迭代器

class FloatRange: def __init__(self, start, stop, step=0.1): self.start = start self.stop = stop self.step = step def __iter__(self): t = self.start while t <= self.stop: yield t t += self.step def __reversed__(self): t = self.stop while t >= self.start: yield t t -= self.step print("正相迭代-----") for n in FloatRange(1.0, 4.0, 0.5): print(n) print("反迭代-----") for x in reversed(FloatRange(1.0, 4.0, 0.5)): print(x)

輸出結果

C:/Python/Python35/python.exe E:/python-intensive-training/s4.py 正相迭代----- 1.0 1.5 2.0 2.5 3.0 3.5 4.0 反迭代----- 4.0 3.5 3.0 2.5 2.0 1.5 1.0 Process finished with exit code 0

四、如何對迭代器做切片操作?

實際案例

有某個文本文件,我們想都去其中某范圍的內容,如100~300行之間的內容,python中文本文件是可迭代對象,我們是否可以使用類似列表切片的方式得到一個100~300行文件內容的生成器?

解決方案

使用標準庫中的itertools.islice,它能返回一個迭代器對象切片的生成器

from itertools import islice f = open('access.log') # # 前500行 # islice(f, 500) # # 100行以后的 # islice(f, 100, None) for line in islice(f,100,300): print(line)

islice每次訓話都會消耗之前的迭代對象

l = range(20) t = iter(l) for x in islice(t, 5, 10): print(x) print('第二次迭代') for x in t: print(x)

輸出結果

C:/Python/Python35/python.exe E:/python-intensive-training/s5.py 5 6 7 8 9 第二次迭代 10 11 12 13 14 15 16 17 18 19 Process finished with exit code 0

五、如何在一個for語句中迭代多個可迭代對象?

實際案例

1、某班學生期末考試成績,語文、數學、英語分別存儲再3個列表中,同時迭代三個列表,計算每個學生的總分(并行)

2、某年紀有四個班,某次考試沒班英語成績分別存儲在四個列表中,依次迭代每個列表,統計全學年成績高于90分人數(串行)

解決方案

并行:使用內置函數zip,它能將多個可迭代對象合并,每次迭代返回一個元組

from random import randint # 申城語文成績,# 40人,分數再60-100之間 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 c, m, e in zip(chinese, math, english): total.append(c + m + e) print(total)

執行結果如下:

C:/Python/Python35/python.exe E:/python-intensive-training/s6.py [232, 234, 259, 248, 241, 236, 245, 253, 275, 238, 240, 239, 283, 256, 232, 224, 201, 255, 206, 239, 254, 216, 287, 268, 235, 223, 289, 221, 266, 222, 231, 240, 226, 235, 255, 232, 235, 250, 241, 225] Process finished with exit code 0

串行:使用標準庫中的itertools.chain,它能將多個可迭代對象連接

from random import randint from itertools import chain # 生成四個班的隨機成績 e1 = [randint(60, 100) for _ in range(40)] e2 = [randint(60, 100) for _ in range(42)] e3 = [randint(60, 100) for _ in range(45)] e4 = [randint(60, 100) for _ in range(50)] # 默認人數=1 count = 0 for s in chain(e1, e2, e3, e4): # 如果當前分數大于90,就讓count+1 if s > 90: count += 1 print(count)

輸出結果

C:/Python/Python35/python.exe E:/python-intensive-training/s6.py 48 Process finished with exit code 0

總結

以上就是這篇文章的全部內容,希望對大家的學習或者工作帶來一定的幫助,如果有疑問大家可以留言交流。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 张北县| 那坡县| 南康市| 河池市| 祁门县| 亳州市| 无为县| 长汀县| 磐安县| 贵州省| 双城市| 连南| 焦作市| 珲春市| 商丘市| 汾阳市| 石门县| 托克托县| 靖安县| 棋牌| 白朗县| 崇左市| 罗江县| 阜南县| 鱼台县| 伊金霍洛旗| 宜宾县| 都昌县| 饶阳县| 耒阳市| 康马县| 革吉县| 江山市| 松原市| 阿鲁科尔沁旗| 衡阳市| 若羌县| 潜江市| 方正县| 林州市| 定州市|