標籤:寫法 轉換 類比 括弧 with open mod += 星期六 控制代碼
初次編輯2017年10月28日,星期六
摘要
一. 上節課複習
二. 協程函數初始化裝飾器
三. send實現耙梳頁
四. 面向過程的程式設計
五. 列表產生式
六. 三元運算式
七.產生器運算式
八. 聲明式編程
作業
今日總結
摘要
引用:百度
- 列表產生式
- 產生器運算式
- 面向過程編程
- 遞迴
一. 上節課複習
- 可迭代的:對象有__iter__方法的都是可迭代的對象
- 迭代器:對象 .iter()得到的結果就是迭代器
- 迭代器的特徵:
- 迭代器.next()取下一個值
- 優點:
- 提供了一種統一的迭代對象的方式,不依賴於索引
- 惰性計算
- 缺點:
- 無法擷取迭代器的長度
- 一次性的,只能往後取值,不能往前退,不能像索引那樣去取得某個位置的值
- 產生器:函數帶有yield關鍵字,那麼這個函數的執行結果就是產生器
- 產生器的本質就是迭代器
def func(): n=0 while True: yield n n += 1g=func()res=next(g)for i in g: pass
- 總結yield功能:
- 相當於把__iter__和__next__方法封裝到函數內部
- 與return相比,return只能返回一次,而yield可以返回多次
- 函數暫停以及繼續啟動並執行狀態是通過yield儲存的
- yield的運算式形式:
food= yield
def eater(name): print(‘%s start to eat ‘%name) while True: food=yield print(‘%s eat %s‘%(name,food))e=eater(‘zhejiangF4‘)
- e.send與next(e)的區別
- 如果函數內yield是運算式形式,那麼必須先next(e)
- 二者的共同之處都是可以讓函數在上次暫停位置繼續運行,不一樣的地方在於send在觸發下一次代碼的執行時,會順便給yield傳一個值
- 另 e.send(None) 和next(e) 效果一樣
二. 協程函數初始化裝飾器
- 簡單裝飾器
def foo(func): def foo1(*args,**kwargs): res = func(*args,**kwargs) next(res) return res #此處理解 產生器是一次性的 return foo1@foo #eater = foo(eater) = foo1def eater(name): print(‘%s start to eat food ‘% name) food_list = [] while True: food = yield food_list print(‘%s get %s, to start eat ‘% (name, food)) food_list.append(food) print(‘Done‘)e = eater(‘鋼蛋‘) #foo1(‘鋼蛋‘)print(e.send(‘123‘))
三. send實現耙梳頁
from urllib.request import urlopendef my_next(func): def foo(*args,**kwargs): res = func(*args,**kwargs) next(res) return res return foo@my_nextdef get(): while True: url = yield res = urlopen(url).read() #耙梳頁傳回值 print(res) #輸出耙梳頁結果g=get()g.send(‘http://www.baidu.com‘)g.send(‘http://www.python.org‘)
四. 面向過程的程式設計
- 面向過程的編程思想:流水線式的編程思想,在程式設計時,需要把整個流程設計出來
- 優點:
- 體繫結構更加清晰
- 簡化程式的複雜度
- 缺點:
- 可擴充性極其差,所以說面向過程的應用情境是:不需要經常變化的軟體
- 實現 #grep -rl ‘python‘ C:\egon
# grep -rl ‘python‘ C:\egonimport os#裝飾器,將產生器next初始化def init(func): def foo(*args,**kwargs): res = func(*args,**kwargs) next(res) return res return foo@initdef search(target): ‘尋找檔案絕對路徑‘ while True: dir_path = yield #此yield放在while外還是內有疑問:yield放在while外就會造成死迴圈,無法進行下次yield g = os.walk(dir_path) #g為迭代器 for i in g: # print(i) for j in i[-1]: file_path = ‘%s\\%s‘%(i[0],j) target.send(file_path)@initdef opener(target): ‘開啟檔案擷取檔案控制代碼‘ while True: file_path = yield with open(file_path) as f: target.send((f,file_path)) #send傳遞兩個檔案時,需加括弧@initdef cat(target): ‘讀取檔案內容‘ while True: f,file_path = yield for line in f: #讀取一行檔案 target.send((line,file_path))@initdef grep(target,pattern): #傳遞兩個參數,其中pattern為要過濾的字串 ‘過濾檔案一行中是否有python‘ while True: line,file_path = yield if pattern in line: target.send(file_path) #需傳遞檔案路徑@initdef printer(): ‘列印檔案路徑‘ while True: file_path = yield print(file_path)g=search(opener(cat(grep(printer(),‘python‘))))g.send(‘C:\\egon‘)
五. 列表產生式
- 普通表達
egg_list = []for i in range(100): egg_list.append(‘egg%s‘% i)print(egg_list)
- 列表產生式表達普通
egg_list = [‘egg%s‘%i for i in range(100)]print(egg_list)
- 列表產生式表達if判斷
#列表內只會添加大於50的數字egg_list = [‘egg%s‘%i for i in range(100) if i >50]print(egg_list)
- 文法
[expression for item1 in interable if condition1 for item2 in interable if condition2 … for itemN in interable if conditionN ]
類似於
res = []for item1 in interable: if condition1: for item2 in interable: if condition2: … for itemN in interable: if conditionN: res.append(expression )
- 實現尋找檔案絕對路徑,以列表的形式表達
import osg = os.walk(‘C:\\egon‘)l = [‘%s\\%s‘% (i[0],j) for i in g for j in i[-1]]print(l)#[‘C:\\egon\\a.txt - 副本.txt‘, ‘C:\\egon\\a.txt.txt‘, ‘C:\\egon\\a\\a.txt.txt‘, ‘C:\\egon\\a\\a2.txt.txt‘, ‘C:\\egon\\b\\a.txt.txt‘, ‘C:\\egon\\b\\a1.txt.txt‘]
六. 三元運算式
name = ‘alex‘name = ‘egon‘res = ‘sb‘ if name ==‘alex‘ else ‘shuai‘print(res) #輸出shuai
七.產生器運算式
- 文法:與列表產生式相似
(expression for item1 in interable if condition1 for item2 in interable if condition2 … for itemN in interable if conditionN )
- 優點:省記憶體,一次只產生一個值在記憶體中
- 應用:讀取一個大檔案的所有內容,並且行處理
#讀取檔案,並去掉每一行兩頭空格f = open(‘a.txt‘)g= (line.strip() for line in f)print(next(g))
注意:因g為可迭代的,因而可以轉換成列表list(g)
八. 聲明式編程
- 消費總額計算
#雞蛋 5 3#特斯拉 10000000.2 5#上衣 1000 3#褲子 2000 3#襪子 100#讀取包含以上資訊的檔案,並計算總共花費#第一種傳統寫法total = []with open(‘b.txt‘,‘r‘,encoding=‘utf-8‘) as f: for line in f: goods=line.split() #split用法及傳回值需加強 # print(goods) res = float(goods[1])*float(goods[-1]) total.append(res)print(total)print(sum(total))#第二種聲明式編程寫法f=open(‘b.txt‘,‘r‘,encoding=‘utf-8‘) #不能用with 否則會IO操作報錯total=(float(line.split()[1])*float(line.split()[-1]) for line in f)print(total)print(sum(total))
- 檔案內容以字典形式嵌套在列表中
#[{‘name‘: ‘襪子‘, ‘price‘: ‘100‘, ‘num‘: ‘3‘}, {‘name‘: ‘襪子‘, ‘price‘: ‘100‘, ‘num‘: ‘3‘}, {‘name‘: ‘襪子‘, ‘price‘: ‘100‘, ‘num‘: ‘3‘}, {‘name‘: ‘襪子‘, ‘price‘: ‘100‘, ‘num‘: ‘3‘}, {‘name‘: ‘襪子‘, ‘price‘: ‘100‘, ‘num‘: ‘3‘}]# 基本寫法res = []d = {}with open(‘b.txt‘,‘r‘,encoding=‘utf-8‘) as f: for line in f: l = line.split() d[‘name‘] = l[0] d[‘price‘] = l[1] d[‘num‘] = l[2] res.append(d)print(res)
- 類比資料庫查詢
with open(‘b.txt‘,‘r‘,encoding=‘utf-8‘) as f: res = (line.split() for line in f) dic_g = ({‘name‘:line[0],‘price‘:line[1],‘num‘:line[2]} for line in res) goods_dic = next(dic_g) print(goods_dic[‘num‘])
- 關於with open() 報錯
with open(‘b.txt‘) as f: d = fprint(d) #有記憶體位址,不是很理解print(next(d)) #報錯
作業
今日總結
Python全棧之路Day22