python高階學習chapter03(迭代相關)

2022-08-14 20:00:14 字數 4289 閱讀 8358

重要概念!!!迭代器,可迭代物件,生成器,很容易繞暈了。

凡是可以使用for進行迴圈的就是可迭代物件,其中可以通過next方法逐步輸出的就是迭代器,生成器的形成有兩種:一種是把列表生成式改成(),一種是帶有yield語句的。

具體的可以看:

接下來進入主題:

如何實現乙個迭代器?

#實現乙個迭代器

from collections import iterator,iterable

#構造迭代器

class weatheriterator(iterator):

def __init__(self,cities):

self.cities = cities

self.index = 0

def getweather(self,city):

r = requests.get('' + city)

dict_data = r.json()['data']['forecast'][0]

return "%s:%s,%s" % (city,dict_data['low'],dict_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)

#生成迭代器物件

weatheriterator = weatheriterator([u'北京',u'南京',u'上海'])

#迭代器物件呼叫next()方法

# print(weatheriterator.__next__())

# print(weatheriterator.__next__())

# print(weatheriterator.__next__())

for x in weatheriterator:

print(x)

python 的迭代協議需要 _iter_() 方法返回乙個實現了 _next_() 方法的迭代器物件。參考:問題引入:

實現乙個連續的浮點數發生器,floatrange,根據給定範圍(start, end) 和步進值,產生一些列的浮點數,例如:floatrange(3,4,0.2),將產生下列序列:

正向:3.0 3.2 …… 4.0

反向:4.0 3.8 …… 3.0

實現思路:

方法一、列表翻轉(但是改變了原列表)

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

l.reverse()

for i in l:

print(i)

方法

二、列表切片(但是得到了和列表等大的列表,浪費空間)

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

for i in l[::-1]:

print(i)

方法三、reversed()函式,返回乙個反轉的迭代器

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

for i in reversed(l):

print(i)

for迴圈是呼叫的_iter_方法,反向迭代呼叫的是_reversed_方法

class floatrange(object):

def __init__(self, start, end, step):

self.dot = self.__get_dot_num(step)

# 有多少個小數點就乘以10的多少次冪,因為浮點數運算不準確,換算成整形數進行計算

self.start = start*pow(10, self.dot)

self.end = end*pow(10, self.dot)

self.step = step*pow(10, self.dot)

def __get_dot_num(self, step):

# 計算step有多少個小數點

if isinstance(step, int):

return step

else:

# 通過round實現計算有多少位小數,首創

for dot in range(len(str(step))+1):

if step == round(step, dot):

return dot

def __iter__(self):

# 正向迭代

while self.start <= self.end:

yield self.start/pow(10, self.dot)

self.start += self.step

def __reversed__(self):

# 反向迭代

while self.end >= self.start:

yield self.end/pow(10,self.dot)

self.end -= self.step

if __name__ == '__main__':

float_num_1 = floatrange(2, 5, 0.1)

float_num_2 = floatrange(2, 5, 0.1)

# 正向迭代

for i in float_num_1:

print(i)

print('_'*60)

# 反向迭代

for x in reversed(float_num_2):

print(x)

問題引入:

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

2、如何依次迭代三個列表(序列):四個班級的英語成績分別存在四個列表中,統計四個班高於90分的總人數

問題1、可以通過索引,也可以使用zip函式將三個列表打包成乙個元組

from random import randint  

def get_result(chinese, math, english):

total =

# 迴圈索引進行取值,畢竟列表等長且成績對應

for index in range(len(chinese)):

return total

或者:def get_result(chinese, math, english):

total =

# 通過zip函式進行迭代,實現同時迭代 3 個物件

for c, m, e in zip(chinese, math, english):

print(c, m, e)

return total

問題2、通過itertools中的chain

from random import randint

from itertools import chain

def get_result(e1, e2, e3):

# 通過chain函式進行連續竄行迭代3個列表

for i in chain(e1, e2, e3):

print(i)

問題引入:如何讀取某個檔案的100~200行的內容呢

是否可以:

f=open()

f[100:200]

方法一、首先使用readlines()讀取全部檔案,然後再用切片操作,但是檔案很大的時候就不適用

f = open()

f_all = f.readlines()

for i in f_all[100:200]:

print(i)

方法

二、使用itertools的islice方法

f = open()

f_need = islice(f, 100, 200)

for i in f_need:

print(i)

參見廖雪峰官網

python 高階學習

2 10 匿名函式 lambda 的理解 print filter lambda s s and len s.strip 0,test none,str end lambda s 相當於 def f s s and len s.strip 相當於 return s and len s.strip l...

Python高階學習

1 2 私有屬性是以雙下劃線 開頭的屬性,在類的外部訪問私有屬性將會丟擲異常,提示沒有這個屬性。3 45 class animal 6 location china 7 def init self,name,age 8 self.name name 9 self.age age 1011 locat...

python高階學習之高階函式

高階函式就是把函式當做引數傳遞的一種函式,例如 執行結果 map 接收乙個函式 f和乙個list,並通過把函式 f 依次作用在 list 的每個元素上,得到乙個新的 list 並返回。執行結果 reduce 函式接收的引數和 map 類似,乙個函式 f,乙個list,但行為和 map 不同,redu...