匿名函數 lambahtml
lambda x,y,z=1:x+y+z
匿名就是沒有名字 def func(x,y,z=1): return x+y+z 匿名 lambda x,y,z=1:x+y+z #與函數有相同的做用域,可是匿名意味着引用計數爲0,使用一次就釋放,除非讓其有名字 func=lambda x,y,z=1:x+y+z func(1,2,3) #讓其有名字就沒有意義
map函數前端
map返回的是一次性迭代器python
map()函數是python內置的高階函數,對傳入的list的每個元素進行映射,返回一個新的映射以後的listmysql
map及下屬2個內置函數與匿名函數的配合使用見文章結尾git
map()函數
map()是 Python 內置的高階函數,它接收一個函數 f 和一個 list,並經過把函數 f 依次做用在 list 的每一個元素上,獲得一個新的 list 並返回。
例如,對於list [1, 2, 3, 4, 5, 6, 7, 8, 9]
若是但願把list的每一個元素都做平方,就能夠用map()函數:
所以,咱們只須要傳入函數f(x)=x*x,就能夠利用map()函數完成這個計算:
def f(x):
return x*x
print map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
輸出結果:
[1, 4, 9, 10, 25, 36, 49, 64, 81]
注意:map()函數不改變原有的 list,而是返回一個新的 list。
利用map()函數,能夠把一個 list 轉換爲另外一個 list,只須要傳入轉換函數。
因爲list包含的元素能夠是任何類型,所以,map() 不只僅能夠處理只包含數值的 list,事實上它能夠處理包含任意類型的 list,只要傳入的函數f能夠處理這種數據類型。
任務
假設用戶輸入的英文名字不規範,沒有按照首字母大寫,後續字母小寫的規則,請利用map()函數,把一個list(包含若干不規範的英文名字)變成一個包含規範英文名字的list:
輸入:['adam', 'LISA', 'barT']
輸出:['Adam', 'Lisa', 'Bart']
def format_name(s):
s1=s[0:1].upper()+s[1:].lower();
return s1;
print map(format_name, ['adam', 'LISA', 'barT'])
filter函數 redis
filter()函數對list中的每個元素帶入f函數進行運算,保留返回結構爲真的元素。算法
filter()函數 filter()函數是 Python 內置的另外一個有用的高階函數,filter()函數接收一個函數 f 和一個list,
這個函數 f 的做用是對每一個元素進行判斷,返回 True或 False,
filter()根據判斷結果自動過濾掉不符合條件的元素,返回由符合條件元素組成的新list。 例如,要從一個list [1, 4, 6, 7, 9, 12, 17]中刪除偶數,保留奇數,首先,要編寫一個判斷奇數的函數: def is_odd(x): return x % 2 == 1 而後,利用filter()過濾掉偶數: filter(is_odd, [1, 4, 6, 7, 9, 12, 17]) 結果:[1, 7, 9, 17] 利用filter(),能夠完成不少有用的功能,例如,刪除 None 或者空字符串: def is_not_empty(s): return s and len(s.strip()) > 0 filter(is_not_empty, ['test', None, '', 'str', ' ', 'END']) 結果:['test', 'str', 'END'] 注意: s.strip(rm) 刪除 s 字符串中開頭、結尾處的 rm 序列的字符。 當rm爲空時,默認刪除空白符(包括'\n', '\r', '\t', ' '),以下: a = ' 123' a.strip() 結果: '123' a='\t\t123\r\n' a.strip() 結果:'123' 任務 請利用filter()過濾出1~100中平方根是整數的數,即結果應該是: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
reduce函數 sql
reduce()函數也是python內置的高階函數,能夠把全部的元素進行f運算,同時能夠傳入三個參數,第三個參數做爲初值。數據庫
python2中可直接使用express
python3中許導入模塊
from functools import reduce
reduce()函數 reduce()函數也是Python內置的一個高階函數。reduce()函數接收的參數和 map()相似,一個函數 f,
一個list,但行爲和 map()不一樣,reduce()傳入的函數 f 必須接收兩個參數,
reduce()對list的每一個元素反覆調用函數f,並返回最終結果值。 例如,編寫一個f函數,接收x和y,返回x和y的和: def f(x, y): return x + y 調用 reduce(f, [1, 3, 5, 7, 9])時,reduce函數將作以下計算: 先計算頭兩個元素:f(1, 3),結果爲4; 再把結果和第3個元素計算:f(4, 5),結果爲9; 再把結果和第4個元素計算:f(9, 7),結果爲16; 再把結果和第5個元素計算:f(16, 9),結果爲25; 因爲沒有更多的元素了,計算結束,返回結果25。 上述計算其實是對 list 的全部元素求和。雖然Python內置了求和函數sum(),可是,利用reduce()求和也很簡單。 reduce()還能夠接收第3個可選參數,做爲計算的初始值。若是把初始值設爲100,計算: reduce(f, [1, 3, 5, 7, 9], 100) 結果將變爲125,由於第一輪計算是: 計算初始值和第一個元素:f(100, 1),結果爲101。 任務 Python內置了求和函數sum(),但沒有求積的函數,請利用recude()來求積: 輸入:[2, 4, 5, 7, 12] 輸出:2*4*5*7*12的結果 def prod(x, y): return x*y print reduce(prod, [2, 4, 5, 7, 12])
內置函數
#注意:內置函數id()能夠返回一個對象的身份,返回值爲整數。這個整數一般對應與該對象在內存中的位置,但這與python的具體實現有關,不該該做爲對身份的定義,即不夠精準,最精準的仍是之內存地址爲準。is運算符用於比較兩個對象的身份,等號比較兩個對象的值,內置函數type()則返回一個對象的類型
#更多內置函數:https://docs.python.org/3/library/functions.html?highlight=built#ascii
參考:http://www.cnblogs.com/linhaifeng/articles/7580830.html#_label4
課程重點
1 什麼是函數? 2 爲何要用函數? 3 函數的分類:內置函數與自定義函數 4 如何自定義函數 語法 定義有參數函數,及有參函數的應用場景 定義無參數函數,及無參函數的應用場景 定義空函數,及空函數的應用場景 5 調用函數 如何調用函數 函數的返回值 函數參數的應用:形參和實參,位置參數,關鍵字參數,默認參數,*args,**kwargs 6 高階函數(函數對象) 7 函數嵌套 8 做用域與名稱空間 9 裝飾器 10 迭代器與生成器及協程函數 11 三元運算,列表解析、生成器表達式 12 函數的遞歸調用 13 內置函數 14 面向過程編程與函數式編程
一:爲什麼用函數之不使用函數的問題
#組織結構不清晰
#代碼冗餘
#沒法統一管理且維護難度大
二:函數分類:
1. 內置函數
2. 自定義函數
三:爲什麼要定義函數
函數即變量,變量必須先定義後使用,未定義而直接引用函數,就至關於在引用一個不存在的變量名
代碼演示?
四:定義函數都幹了哪些事?
只檢測語法,不執行代碼
五:如何定義函數(函數名要能反映其意義)
def ...
六:定義函數的三種形式
無參:應用場景僅僅只是執行一些操做,好比與用戶交互,打印
有參:須要根據外部傳進來的參數,才能執行相應的邏輯,好比統計長度,求最大值最小值
空函數:設計代碼結構
七 :函數的調用
1 先找到名字
2 根據名字調用代碼
函數的返回值?
0->None
1->返回1個值
多個->元組
何時該有?
調用函數,通過一系列的操做,最後要拿到一個明確的結果,則必需要有返回值
一般有參函數須要有返回值,輸入參數,通過計算,獲得一個最終的結果
何時不須要有?
調用函數,僅僅只是執行一系列的操做,最後不須要獲得什麼結果,則無需有返回值
一般無參函數不須要有返回值
八:函數調用的三種形式
1 語句形式:foo()
2 表達式形式:3*len('hello')
4 當中另一個函數的參數:range(len('hello'))
九:函數的參數:
1 形參和實參定義
2 形參即變量名,實參即變量值,函數調用則將值綁定到名字上,函數調用結束,解除綁定
3 具體應用
位置參數:按照從左到右的順序定義的參數
位置形參:必選參數
位置實參:按照位置給形參傳值
關鍵字參數:按照key=value的形式定義實參
無需按照位置爲形參傳值
注意的問題:
1. 關鍵字實參必須在位置實參右面
2. 對同一個形參不能重複傳值
默認參數:形參在定義時就已經爲其賦值
能夠傳值也能夠不傳值,常常須要變得參數定義成位置形參,變化較小的參數定義成默認參數(形參)
注意的問題:
1. 只在定義時賦值一次
2. 默認參數的定義應該在位置形參右面
3. 默認參數一般應該定義成不可變類型
可變長參數:
針對實參在定義時長度不固定的狀況,應該從形參的角度找到能夠接收可變長實參的方案,這就是可變長參數(形參)
而實參有按位置和按關鍵字兩種形式定義,針對這兩種形式的可變長,形參也應該有兩種解決方案,分別是*args,**kwargs
===========*args=========== def foo(x,y,*args): print(x,y) print(args) foo(1,2,3,4,5) def foo(x,y,*args): print(x,y) print(args) foo(1,2,*[3,4,5]) def foo(x,y,z): print(x,y,z) foo(*[1,2,3]) ===========**kwargs=========== def foo(x,y,**kwargs): print(x,y) print(kwargs) foo(1,y=2,a=1,b=2,c=3) def foo(x,y,**kwargs): print(x,y) print(kwargs) foo(1,y=2,**{'a':1,'b':2,'c':3}) def foo(x,y,z): print(x,y,z) foo(**{'z':1,'x':2,'y':3}) ===========*args+**kwargs=========== def foo(x,y): print(x,y) def wrapper(*args,**kwargs): print('====>') foo(*args,**kwargs)
命名關鍵字參數:*後定義的參數,必須被傳值(有默認值的除外),且必須按照關鍵字實參的形式傳遞
能夠保證,傳入的參數中必定包含某些關鍵字
def foo(x,y,*args,a=1,b,**kwargs): print(x,y) print(args) print(a) print(b) print(kwargs) foo(1,2,3,4,5,b=3,c=4,d=5)
結果:
1 2
(3, 4, 5)
1
3
{'c': 4, 'd': 5}
十 階段性練習
一、寫函數,,用戶傳入修改的文件名,與要修改的內容,執行函數,完成批了修改操做
二、寫函數,計算傳入字符串中【數字】、【字母】、【空格] 以及 【其餘】的個數
三、寫函數,判斷用戶傳入的對象(字符串、列表、元組)長度是否大於5。
四、寫函數,檢查傳入列表的長度,若是大於2,那麼僅保留前兩個長度的內容,並將新內容返回給調用者。
五、寫函數,檢查獲取傳入列表或元組對象的全部奇數位索引對應的元素,並將其做爲新列表返回給調用者。
奇數的語句print x[::2]
偶數的語句print x[1::2]
六、寫函數,檢查字典的每個value的長度,若是大於2,那麼僅保留前兩個長度的內容,並將新內容返回給調用者。
dic = {"k1": "v1v1", "k2": [11,22,33,44]}
PS:字典中的value只能是字符串或列表
#題目一 def modify_file(filename,old,new): import os with open(filename,'r',encoding='utf-8') as read_f,\ open('.bak.swap','w',encoding='utf-8') as write_f: for line in read_f: if old in line: line=line.replace(old,new) write_f.write(line) os.remove(filename) os.rename('.bak.swap',filename) modify_file('/Users/jieli/PycharmProjects/爬蟲/a.txt','alex','SB') #題目二 def check_str(msg): res={ 'num':0, 'string':0, 'space':0, 'other':0, } for s in msg: if s.isdigit(): res['num']+=1 elif s.isalpha(): res['string']+=1 elif s.isspace(): res['space']+=1 else: res['other']+=1 return res res=check_str('hello name:aSB passowrd:alex3714') print(res) #題目三:略 #題目四 def func1(seq): if len(seq) > 2: seq=seq[0:2] return seq print(func1([1,2,3,4])) #題目五 def func2(seq): return seq[::2] print(func2([1,2,3,4,5,6,7])) #題目六 def func3(dic): d={} for k,v in dic.items(): if len(v) > 2: d[k]=v[0:2] return d print(func3({'k1':'abcdef','k2':[1,2,3,4],'k3':('a','b','c')}))
=======================本節課新內容==========================
一:函數對象:函數是第一類對象,即函數能夠看成數據傳遞
1 能夠被引用
2 能夠看成參數傳遞
3 返回值能夠是函數
3 能夠看成容器類型的元素
#利用該特性,優雅的取代多分支的if
def foo(): print('foo') def bar(): print('bar') dic={ 'foo':foo, 'bar':bar, } while True: choice=input('>>: ').strip() if choice in dic: dic[choice]()
二:函數的嵌套
1 函數的嵌套調用
def max(x,y): return x if x > y else y def max4(a,b,c,d): res1=max(a,b) res2=max(res1,c) res3=max(res2,d) return res3 print(max4(1,2,3,4))
2 函數的嵌套定義
def f1(): def f2(): def f3(): print('from f3') f3() f2() f1() #f3() #報錯
三 名稱空間和做用域:
名稱空間:存放名字的地方,三種名稱空間,(以前遺留的問題x=1,1存放於內存中,那名字x存放在哪裏呢?名稱空間正是存放名字x與1綁定關係的地方)
加載順序是?
名字的查找順序?(在全局沒法查看局部的,在局部能夠查看全局的)
max=1 def f1(): # max=2 def f2(): # max=3 print(max) f2() f1() print(max)
做用域即範圍
- 全局範圍:全局存活,全局有效
- 局部範圍:臨時存活,局部有效
- 做用域關係是在函數定義階段就已經固定的,與函數的調用位置無關,以下
x=1 def f1(): def f2(): rint(x) return f2 def f3(func): x=2 func() f3(f1())
查看做用域:globals(),locals()
global
nonlocal
LEGB 表明名字查找順序: locals -> enclosing function -> globals -> __builtins__
locals 是函數內的名字空間,包括局部變量和形參
enclosing 外部嵌套函數的名字空間(閉包中常見)
globals 全局變量,函數定義所在模塊的名字空間
builtins 內置模塊的名字空間
四:閉包:內部函數包含對外部做用域而非全局做用域的引用
提示:以前咱們都是經過參數將外部的值傳給函數,閉包提供了另一種思路,包起來嘍,包起呦,包起來哇
def counter(): n=0 def incr(): nonlocal n x=n n+=1 return x return incr c=counter() print(c()) print(c()) print(c()) print(c.__closure__[0].cell_contents) #查看閉包的元素
閉包的意義:返回的函數對象,不只僅是一個函數對象,在該函數外還包裹了一層做用域,這使得,該函數不管在何處調用,優先使用本身外層包裹的做用域
應用領域:延遲計算(原來咱們是傳參,如今咱們是包起來)
from urllib.request import urlopen def index(url): def get(): return urlopen(url).read() return get baidu=index('http://www.baidu.com') print(baidu().decode('utf-8'))
五: 裝飾器(閉包函數的一種應用場景)
1 爲什麼要用裝飾器:
開放封閉原則:對修改封閉,對擴展開放
2 什麼是裝飾器
裝飾器他人的器具,自己能夠是任意可調用對象,被裝飾者也能夠是任意可調用對象。
強調裝飾器的原則:1 不修改被裝飾對象的源代碼 2 不修改被裝飾對象的調用方式
裝飾器的目標:在遵循1和2的前提下,爲被裝飾對象添加上新功能
3. 先看簡單示範
import time def timmer(func): def wrapper(*args,**kwargs): start_time=time.time() res=func(*args,**kwargs) stop_time=time.time() print('run time is %s' %(stop_time-start_time)) return res return wrapper ##@裝飾器 要給foo添加功能,則寫在def foo頭部,等同於 foo=timmer(foo) @timmer def foo(): time.sleep(3) print('from foo') foo()
4
def auth(driver='file'): def auth2(func): def wrapper(*args,**kwargs): name=input("user: ") pwd=input("pwd: ") if driver == 'file': if name == 'egon' and pwd == '123': print('login successful') res=func(*args,**kwargs) return res elif driver == 'ldap': print('ldap') return wrapper return auth2 @auth(driver='file') def foo(name): print(name) foo('egon')
5 裝飾器語法:
被裝飾函數的正上方,單獨一行
@deco1
@deco2
@deco3
def foo():
pass
foo=deco1(deco2(deco3(foo)))
6 裝飾器補充:wraps
from functools import wraps def deco(func): @wraps(func) #加在最內層函數正上方 def wrapper(*args,**kwargs): return func(*args,**kwargs) return wrapper @deco def index(): '''哈哈哈哈''' print('from index') print(index.__doc__)
7 裝飾器練習
一:編寫函數,(函數執行的時間是隨機的)
二:編寫裝飾器,爲函數加上統計時間的功能
三:編寫裝飾器,爲函數加上認證的功能
四:編寫裝飾器,爲多個函數加上認證的功能(用戶的帳號密碼來源於文件),要求登陸成功一次,後續的函數都無需再輸入用戶名和密碼
注意:從文件中讀出字符串形式的字典,能夠用eval('{"name":"egon","password":"123"}')轉成字典格式
五:編寫裝飾器,爲多個函數加上認證功能,要求登陸成功一次,在超時時間內無需重複登陸,超過了超時時間,則必須從新登陸
六:編寫下載網頁內容的函數,要求功能是:用戶傳入一個url,函數返回下載頁面的結果
七:爲題目五編寫裝飾器,實現緩存網頁內容的功能:
具體:實現下載的頁面存放於文件中,若是文件內有值(文件大小不爲0),就優先從文件中讀取網頁內容,不然,就去下載,而後存到文件中
擴展功能:用戶能夠選擇緩存介質/緩存引擎,針對不一樣的url,緩存到不一樣的文件中
八:還記得咱們用函數對象的概念,製做一個函數字典的操做嗎,來來來,咱們有更高大上的作法,在文件開頭聲明一個空字典,而後在每一個函數前加上裝飾器,完成自動添加到字典的操做
九 編寫日誌裝飾器,實現功能如:一旦函數f1執行,則將消息2017-07-21 11:12:11 f1 run寫入到日誌文件中,日誌文件路徑能夠指定
注意:時間格式的獲取
import time
time.strftime('%Y-%m-%d %X')
#題目一:略 #題目二:略 #題目三:略 #題目四: db='db.txt' login_status={'user':None,'status':False} def auth(auth_type='file'): def auth2(func): def wrapper(*args,**kwargs): if login_status['user'] and login_status['status']: return func(*args,**kwargs) if auth_type == 'file': with open(db,encoding='utf-8') as f: dic=eval(f.read()) name=input('username: ').strip() password=input('password: ').strip() if name in dic and password == dic[name]: login_status['user']=name login_status['status']=True res=func(*args,**kwargs) return res else: print('username or password error') elif auth_type == 'sql': pass else: pass return wrapper return auth2 @auth() def index(): print('index') @auth(auth_type='file') def home(name): print('welcome %s to home' %name) # index() # home('egon') #題目五 import time,random user={'user':None,'login_time':None,'timeout':0.000003,} def timmer(func): def wrapper(*args,**kwargs): s1=time.time() res=func(*args,**kwargs) s2=time.time() print('%s' %(s2-s1)) return res return wrapper def auth(func): def wrapper(*args,**kwargs): if user['user']: timeout=time.time()-user['login_time'] if timeout < user['timeout']: return func(*args,**kwargs) name=input('name>>: ').strip() password=input('password>>: ').strip() if name == 'egon' and password == '123': user['user']=name user['login_time']=time.time() res=func(*args,**kwargs) return res return wrapper @auth def index(): time.sleep(random.randrange(3)) print('welcome to index') @auth def home(name): time.sleep(random.randrange(3)) print('welcome %s to home ' %name) index() home('egon') #題目六:略 #題目七:簡單版本 import requests import os cache_file='cache.txt' def make_cache(func): def wrapper(*args,**kwargs): if not os.path.exists(cache_file): with open(cache_file,'w'):pass if os.path.getsize(cache_file): with open(cache_file,'r',encoding='utf-8') as f: res=f.read() else: res=func(*args,**kwargs) with open(cache_file,'w',encoding='utf-8') as f: f.write(res) return res return wrapper @make_cache def get(url): return requests.get(url).text # res=get('https://www.python.org') # print(res) #題目七:擴展版本 import requests,os,hashlib engine_settings={ 'file':{'dirname':'./db'}, 'mysql':{ 'host':'127.0.0.1', 'port':3306, 'user':'root', 'password':'123'}, 'redis':{ 'host':'127.0.0.1', 'port':6379, 'user':'root', 'password':'123'}, } def make_cache(engine='file'): if engine not in engine_settings: raise TypeError('egine not valid') def deco(func): def wrapper(url): if engine == 'file': m=hashlib.md5(url.encode('utf-8')) cache_filename=m.hexdigest() cache_filepath=r'%s/%s' %(engine_settings['file']['dirname'],cache_filename) if os.path.exists(cache_filepath) and os.path.getsize(cache_filepath): return open(cache_filepath,encoding='utf-8').read() res=func(url) with open(cache_filepath,'w',encoding='utf-8') as f: f.write(res) return res elif engine == 'mysql': pass elif engine == 'redis': pass else: pass return wrapper return deco @make_cache(engine='file') def get(url): return requests.get(url).text # print(get('https://www.python.org')) print(get('https://www.baidu.com')) #題目八 route_dic={} def make_route(name): def deco(func): route_dic[name]=func return deco @make_route('select') def func1(): print('select') @make_route('insert') def func2(): print('insert') @make_route('update') def func3(): print('update') @make_route('delete') def func4(): print('delete') print(route_dic) #題目九 import time import os def logger(logfile): def deco(func): if not os.path.exists(logfile): with open(logfile,'w'):pass def wrapper(*args,**kwargs): res=func(*args,**kwargs) with open(logfile,'a',encoding='utf-8') as f: f.write('%s %s run\n' %(time.strftime('%Y-%m-%d %X'),func.__name__)) return res return wrapper return deco @logger(logfile='aaaaaaaaaaaaaaaaaaaaa.log') def index(): print('index') index()
用戶登陸裝飾
import time user,passwd = 'alex','abc123' def auth(auth_type): print("auth func:",auth_type) def outer_wrapper(func): def wrapper(*args, **kwargs): print("wrapper func args:", *args, **kwargs) if auth_type == "local": username = input("Username:").strip() password = input("Password:").strip() if user == username and passwd == password: print("\033[32;1mUser has passed authentication\033[0m") res = func(*args, **kwargs) # from home print("---after authenticaion ") return res else: exit("\033[31;1mInvalid username or password\033[0m") elif auth_type == "ldap": print("搞毛線ldap,不會。。。。") return wrapper return outer_wrapper def index(): print("welcome to index page") @auth(auth_type="local") # home = wrapper() def home(): print("welcome to home page") return "from home" @auth(auth_type="ldap") def bbs(): print("welcome to bbs page") index() print(home()) #wrapper() bbs()
六:迭代器
迭代的概念:重複的過程稱爲迭代,每次重複即一次迭代,而且每次迭代的結果是下一次迭代的初始值
# while True: #只知足重複,於是不是迭代 # print('====>') #迭代 l=[1,2,3] count=0 while count < len(l): #只知足重複,於是不是迭代 print('====>',l[count]) count+=1
#其餘
爲什麼要有迭代器?
可迭代的對象?
哪些是可迭代對象?
迭代器?
l={'a':1,'b':2,'c':3,'d':4,'e':5} i=l.__iter__() #等於i=iter(l) print(next(i)) print(next(i)) print(next(i)) StopIteration
for循環
迭代器的優缺點:
優勢:
提供統一的且不依賴於索引的迭代方式
惰性計算,節省內存
缺點:
沒法獲取長度
一次性的,只能日後走,不能往前退
迭代器協議
練習:判斷如下對象哪一個是可迭代對象,哪一個是迭代器對象
s='hello'
l=[1,2,3,4]
t=(1,2,3)
d={'a':1}
set={1,2,3}
f=open('a.txt')
七 生成器
yield:
把函數作成迭代器
對比return,能夠返回屢次值,掛起函數的運行狀態
經過列表生成式,咱們能夠直接建立一個列表。可是,受到內存限制,列表容量確定是有限的。並且,建立一個包含100萬個元素的列表,不只佔用很大的存儲空間,若是咱們僅僅須要訪問前面幾個元素,那後面絕大多數元素佔用的空間都白白浪費了。
因此,若是列表元素能夠按照某種算法推算出來,那咱們是否能夠在循環的過程當中不斷推算出後續的元素呢?這樣就沒必要建立完整的list,從而節省大量的空間。在Python中,這種一邊循環一邊計算的機制,稱爲生成器:generator。
要建立一個generator,有不少種方法。第一種方法很簡單,只要把一個列表生成式的[]
改爲()
,就建立了一個generator
列表生成式 a = [ i*2 for i in range(10)]
>>> L =[x *x forx inrange(10)]
>>> L
[
0
,
1
,
4
,
9
,
16
,
25
,
36
,
49
,
64
,
81
]
>>> g
=
(x
*
x
for
x
in
range
(
10
))
>>> g
<generator
object
<genexpr> at
0x1022ef630
>
Python之路,Day4 - Python基礎4 (new版): http://www.cnblogs.com/alex3714/articles/5765046.html
若是一個函數定義中包含yield
關鍵字,那麼這個函數就再也不是一個普通函數,而是一個generator
# def foo(): # return 1 # return 2 # return 3 # # res=foo() # print(res) def foo(): yield 1 yield 2 yield 3 res=foo() print(res) from collections import Iterable,Iterator print(isinstance(res,Iterator)) print(next(res)) print(next(res)) print(next(res)) #應用一: def counter(n): print('start') i=0 while i < n: yield i i+=1 print('end') c=counter(5) # print(next(c)) #0 # print(next(c)) #1 # print(next(c)) #2 # print(next(c)) #3 # print(next(c)) #4 # print(next(c)) #5 --->沒有yield,拋出StopIteration for i in counter(5): print(i) #應用二:管道tail -f a.txt |grep 'python' import time def tail(filepath): with open(filepath,encoding='utf-8') as f: f.seek(0,2) while True: line=f.readline() if line: yield line else: time.sleep(0.5) def grep(pattern,lines): for line in lines: if pattern in line: yield line for i in grep('python',tail('a.txt')): print(i) #協程函數 def eater(name): print('%s說:我開動啦' %name) food_list=[] while True: food=yield food_list food_list.append(food) print('%s 吃了 %s' %(name,food)) e=eater('egon') e.send(None) #next(e) #初始化裝飾器, e.close() #關閉 #面向過程編程: import os def init(func): def wrapper(*args,**kwargs): g=func(*args,**kwargs) next(g) return g return wrapper def search(file_dir,target): for par_dir,_,files in os.walk(file_dir): for file in files: filepath='%s\%s' %(par_dir,file) target.send(filepath) @init def opener(target): while True: filepath=yield with open(filepath) as f: target.send((f,filepath)) @init def cat(target): while True: res=False f,filepath=yield res for line in f: print(line,end='') res=target.send((line,filepath)) if res: break @init def grep(pattern,target): res = False while True: line,filepath=yield res res=False if pattern in line: res=True target.send(filepath) @init def printer(): while True: filepath=yield print(filepath) search(r'C:\Users\Administrator\PycharmProjects\test\字符編碼\a', opener(cat(grep('python',printer()))))
#注意:target.send(...)在拿到target的返回值後纔算執行結束 import os def init(func): def wrapper(*args,**kwargs): g=func(*args,**kwargs) next(g) return g return wrapper @init def search(target): while True: search_dir=yield for par_dir,_,files in os.walk(search_dir): for file in files: file_abs_path=r'%s\%s' %(par_dir,file) # print(file_abs_path) target.send(file_abs_path) @init def opener(target): while True: file_abs_path=yield with open(file_abs_path,encoding='utf-8') as f: target.send((file_abs_path,f)) @init def cat(target): while True: file_abs_path,f=yield print('檢索文件',file_abs_path) for line in f: tag=target.send((file_abs_path,line)) print('檢索文件的行: %s' %line) if tag: break @init def grep(pattern,target): tag=False while True: file_abs_path,line=yield tag tag=False if pattern in line: tag=True target.send(file_abs_path) @init def printer(): while True: file_abs_path=yield print('過濾出的結果=========>',file_abs_path) search_dir=r'C:\Users\Administrator\PycharmProjects\test\函數備課\a' e=search(opener(cat(grep('python',printer())))) e.send(search_dir)
八:三元表達式,列表推導式,生成器表達式
==============================#三元表達式
name='alex' name='linhaifeng' res='SB' if name == 'alex' else 'shuai' print(res)
==============================列表推導式
------------------1:引子
生一筐雞蛋
egg_list=[]
for i in range(10):
egg_list.append('雞蛋%s' %i)
egg_list=['雞蛋%s' %i for i in range(10)] #列表解析
------------------2:語法
[expression for item1 in iterable1 if condition1
for item2 in iterable2 if condition2
...
for itemN in iterableN if conditionN
]
相似於
res=[]
for item1 in iterable1:
if condition1:
for item2 in iterable2:
if condition2
...
for itemN in iterableN:
if conditionN:
res.append(expression)
------------------3:優勢
方便,改變了編程習慣,聲明式編程
------------------4:應用
l1=[3,-4,-1,5,7,9]
[i**i for i in l1]
[i for i in l1 if i >0]
s='egon'
[(i,j) for i in l1 if i>0 for j in s] #元組合必須加括號[i,j ...]非法
==============================生成器表達式
------------------1:引子
生一筐雞蛋變成給你一隻老母雞,用的時候就下蛋,這也是生成器的特性
egg_list=[]
for i in range(10):
egg_list.append('雞蛋%s' %i)
chicken=('雞蛋%s' %i for i in range(10))
>>> chicken
<generator object <genexpr> at 0x10143f200>
>>> next(chicken)
'雞蛋5'
------------------2:語法
語法與列表推導式相似,只是[]->()
(expression for item1 in iterable1 if condition1
for item2 in iterable2 if condition2
...
for itemN in iterableN if conditionN
)
------------------3:優勢
省內存,一次只產生一個值在內存中
------------------4:應用
讀取一個大文件的全部內容,而且處理行
f=open('a.txt')
g=(line.strip() for line in f)
list(g) #因g可迭代,於是能夠轉成列表
------------------5:示例
#一
with open('a.txt') as f:
print(max(len(line) for line in f))
print(sum(len(line) for line in f)) #求包換換行符在內的文件全部的字節數,爲什麼獲得的值爲0?
#二
print(max(len(line) for line in open('a.txt')))
print(sum(len(line) for line in open('a.txt')))
#三
with open('a.txt') as f:
g=(len(line) for line in f)
print(sum(g)) #爲什麼報錯?
==============================聲明式編程
文件a.txt內容
apple 10 3
tesla 100000 1
mac 3000 2
lenovo 30000 3
chicken 10 3
f=open('a.py')
#求花了多少錢
g=(line.split() for line in f)
sum(float(price)*float(count) for _,price,count in g)
模擬數據庫查詢
>>> f=open('a.txt')
>>> g=(line.split() for line in f)
>>> goods_l=[{'name':n,'price':p,'count':c} for n,p,c in g]
過濾查詢
>>> goods_l=[{'name':n,'price':p,'count':c} for n,p,c in g if float(p) > 10000]
九:匿名函數lambda
匿名就是沒有名字
def func(x,y,z=1):
return x+y+z
匿名
lambda x,y,z=1:x+y+z #與函數有相同的做用域,可是匿名意味着引用計數爲0,使用一次就釋放,除非讓其有名字
func=lambda x,y,z=1:x+y+z
func(1,2,3)
#讓其有名字就沒有意義
有名函數:循環使用,保存了名字,經過名字就能夠重複引用函數功能
匿名函數:一次性使用,隨時隨時定義
應用:max,min,sorted,map,reduce,filter
十 內建函數
注意:內置函數id()能夠返回一個對象的身份,返回值爲整數。這個整數一般對應與該對象在內存中的位置,但這與python的具體實現有關,不該該做爲對身份的定義,即不夠精準,最精準的仍是之內存地址爲準。is運算符用於比較兩個對象的身份,等號比較兩個對象的值,內置函數type()則返回一個對象的類型
字典的運算:最小值,最大值,排序 salaries={ 'egon':3000, 'alex':100000000, 'wupeiqi':10000, 'yuanhao':2000 } 迭代字典,取得是key,於是比較的是key的最大和最小值 >>> max(salaries) 'yuanhao' >>> min(salaries) 'alex' 能夠取values,來比較 >>> max(salaries.values()) >>> min(salaries.values()) 但一般咱們都是想取出,工資最高的那我的名,即比較的是salaries的值,獲得的是鍵 >>> max(salaries,key=lambda k:salary[k]) 'alex' >>> min(salaries,key=lambda k:salary[k]) 'yuanhao' 也能夠經過zip的方式實現 salaries_and_names=zip(salaries.values(),salaries.keys()) 先比較值,值相同則比較鍵 >>> max(salaries_and_names) (100000000, 'alex') salaries_and_names是迭代器,於是只能訪問一次 >>> min(salaries_and_names) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: min() arg is an empty sequence sorted(iterable,key=None,reverse=False)
#字符串能夠提供的參數 's' None >>> format('some string','s') 'some string' >>> format('some string') 'some string' #整形數值能夠提供的參數有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None >>> format(3,'b') #轉換成二進制 '11' >>> format(97,'c') #轉換unicode成字符 'a' >>> format(11,'d') #轉換成10進制 '11' >>> format(11,'o') #轉換成8進制 '13' >>> format(11,'x') #轉換成16進制 小寫字母表示 'b' >>> format(11,'X') #轉換成16進制 大寫字母表示 'B' >>> format(11,'n') #和d同樣 '11' >>> format(11) #默認和d同樣 '11' #浮點數能夠提供的參數有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None >>> format(314159267,'e') #科學計數法,默認保留6位小數 '3.141593e+08' >>> format(314159267,'0.2e') #科學計數法,指定保留2位小數 '3.14e+08' >>> format(314159267,'0.2E') #科學計數法,指定保留2位小數,採用大寫E表示 '3.14E+08' >>> format(314159267,'f') #小數點計數法,默認保留6位小數 '314159267.000000' >>> format(3.14159267000,'f') #小數點計數法,默認保留6位小數 '3.141593' >>> format(3.14159267000,'0.8f') #小數點計數法,指定保留8位小數 '3.14159267' >>> format(3.14159267000,'0.10f') #小數點計數法,指定保留10位小數 '3.1415926700' >>> format(3.14e+1000000,'F') #小數點計數法,無窮大轉換成大小字母 'INF' #g的格式化比較特殊,假設p爲格式中指定的保留小數位數,先嚐試採用科學計數法格式化,獲得冪指數exp,若是-4<=exp<p,則採用小數計數法,並保留p-1-exp位小數,不然按小數計數法計數,並按p-1保留小數位數 >>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學計數法計數,保留0位小數點 '3e-05' >>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學計數法計數,保留1位小數點 '3.1e-05' >>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學計數法計數,保留2位小數點 '3.14e-05' >>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學計數法計數,保留0位小數點,E使用大寫 '3.14E-05' >>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp<p成立,按小數計數法計數,保留0位小數點 '3' >>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp<p成立,按小數計數法計數,保留1位小數點 '3.1' >>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp<p成立,按小數計數法計數,保留2位小數點 '3.14' >>> format(0.00003141566,'.1n') #和g相同 '3e-05' >>> format(0.00003141566,'.3n') #和g相同 '3.14e-05' >>> format(0.00003141566) #和g相同 '3.141566e-05'
十一:內建函數補充(結合lambda)
字典的運算:最小值,最大值,排序
salaries={
'egon':3000,
'alex':100000000,
'wupeiqi':10000,
'yuanhao':2000
}
迭代字典,取得是key,於是比較的是key的最大和最小值
>>> max(salaries)
'yuanhao'
>>> min(salaries)
'alex'
能夠取values,來比較
>>> max(salaries.values())
100000000
>>> min(salaries.values())
2000
但一般咱們都是想取出,工資最高的那我的名,即比較的是salaries的值,獲得的是鍵
>>> max(salaries,key=lambda k:salary[k])
'alex'
>>> min(salaries,key=lambda k:salary[k])
'yuanhao'
也能夠經過zip的方式實現
salaries_and_names=zip(salaries.values(),salaries.keys())
先比較值,值相同則比較鍵
>>> max(salaries_and_names)
(100000000, 'alex')
salaries_and_names是迭代器,於是只能訪問一次
>>> min(salaries_and_names)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: min() arg is an empty sequence
sorted(iterable,key=None,reverse=False)
#eval與compile
eval(str,[,globasl[,locals]])
eval('1+2+max(3,9,100)+1.3')
my_globals={'x':1}
my_locals={'x':2}
eval('1+x',my_globals,my_locals)
exec('for i in range(10):print("i")')
一樣能夠指定本身的名稱空間
compile(str,filename,kind)
filename:用於追蹤str來自於哪一個文件,若是不想追蹤就能夠不定義
kind能夠是:single表明一條語句,exec表明一組語句,eval表明一個表達式
s='for i in range(10):print(i)' code=compile(s,'','exec') exec(code) s='1+2+3' code=compile(s,'','eval') eval(code)
十二:函數的遞歸調用
圖解:遞推和回溯
# salary(5)=salary(4)+300 # salary(4)=salary(3)+300 # salary(3)=salary(2)+300 # salary(2)=salary(1)+300 # salary(1)=100 # # salary(n)=salary(n-1)+300 n>1 # salary(1) =100 n=1 def salary(n): if n == 1: return 100 return salary(n-1)+300 print(salary(5))
函數在調用時,直接或間接調用了自身,就是遞歸調用
def fac(n):#階乘運算
if n == 1:return 1
else:return n*fib(n-1)
遞歸效率低,須要在進入下一次遞歸時保留當前的狀態,見51cto博客
解決方法是尾遞歸,即在函數的最後一步(而非最後一行)調用本身
可是python又沒有尾遞歸,且對遞歸層級作了限制
1. 必須有一個明確的結束條件
2. 每次進入更深一層遞歸時,問題規模相比上次遞歸都應有所減小
3. 遞歸效率不高,遞歸層次過多會致使棧溢出(在計算機中,函數調用是經過棧(stack)這種數據結構實現的,每當進入一個函數調用,棧就會加一層棧幀,每當函數返回,棧就會減一層棧幀。因爲棧的大小不是無限的,因此,遞歸調用的次數過多,會致使棧溢出)
尾遞歸優化:http://egon09.blog.51cto.com/9161406/1842475
>>> sys.getrecursionlimit()
1000
>>> n=1
>>> def test():
... global n
... n+=1
... print(n)
... test()
...
>>> test()
>>> sys.setrecursionlimit(10000)
>>> test() #能夠遞歸10000層了
雖然能夠設置,可是由於不是尾遞歸,仍然要保存棧,內存大小必定,不可能無限遞歸
十三 階段性練習:
1 文件內容以下,標題爲:姓名,性別,年紀,薪資
egon male 18 3000
alex male 38 30000
wupeiqi female 28 20000
yuanhao female 28 10000
要求:
從文件中取出每一條記錄放入列表中,
列表的每一個元素都是{'name':'egon','sex':'male','age':18,'salary':3000}的形式
2 根據1獲得的列表,取出薪資最高的人的信息
3 根據1獲得的列表,取出最年輕的人的信息
4 根據1獲得的列表,將每一個人的信息中的名字映射成首字母大寫的形式
5 根據1獲得的列表,過濾掉名字以a開頭的人的信息
6 使用遞歸打印斐波那契數列(前兩個數的和獲得第三個數)
0 1 1 2 3 4 7...
7 l=[1,2,[3,[4,5,6,[7,8,[9,10,[11,12,13,[14,15]]]]]]]
一個列表嵌套不少層,用遞歸取出全部的值
#1 with open('db.txt') as f: items=(line.split() for line in f) info=[{'name':name,'sex':sex,'age':age,'salary':salary} \ for name,sex,age,salary in items] print(info) #2 print(max(info,key=lambda dic:dic['salary'])) #3 print(min(info,key=lambda dic:dic['age'])) # 4 info_new=map(lambda item:{'name':item['name'].capitalize(), 'sex':item['sex'], 'age':item['age'], 'salary':item['salary']},info) print(list(info_new)) #5 g=filter(lambda item:item['name'].startswith('a'),info) print(list(g)) #6 #非遞歸 def fib(n): a,b=0,1 while a < n: print(a,end=' ') a,b=b,a+b print() fib(10) #遞歸 def fib(a,b,stop): if a > stop: return print(a,end=' ') fib(b,a+b,stop) fib(0,1,10) #7 l=[1,2,[3,[4,5,6,[7,8,[9,10,[11,12,13,[14,15]]]]]]] def get(seq): for item in seq: if type(item) is list: get(item) else: print(item) get(l)
十四:二分法
l=[1,2,10,2,30,40,33,22,99,31] def search(num,l): print(l) if len(l) > 1: mid=len(l)//2 if num > l[mid]: #in the right l=l[mid:] search(num,l) elif num < l[mid]: #in the left l=l[:mid] search(num,l) else: print('find it') else: if num == l[0]: print('find it') else: print('not exists') search(100,l)
def search(seq,num): print(seq) if len(seq) == 1: if num == seq[0]: print('you find it') else: print('not exist') return mid=len(seq)//2 if num > seq[mid]: #in the right seq=seq[mid:] search(seq,num) elif num < seq[mid]: #in the left seq=seq[:mid] search(seq,num) else: print('find it') search(l,3)
十五:面向過程編程,函數式編程
峯哥原創面向過程解釋:
函數的參數傳入,是函數吃進去的食物,而函數return的返回值,是函數拉出來的結果,面向過程的思路就是,把程序的執行當作一串首尾相連的函數,一個函數吃,拉出的東西給另一個函數吃,另一個函數吃了再繼續拉給下一個函數吃。。。
面向過程:機械式思惟,流水線式編程
例如:
用戶登陸流程:前端接收處理用戶請求-》將用戶信息傳給邏輯層,邏輯詞處理用戶信息-》將用戶信息寫入數據庫
驗證用戶登陸流程:數據庫查詢/處理用戶信息-》交給邏輯層,邏輯層處理用戶信息-》用戶信息交給前端,前端顯示用戶信息
函數式編程:http://egon09.blog.51cto.com/9161406/1842475
array=[1,3,4,71,2] ret=[] for i in array: ret.append(i**2) print(ret) #若是咱們有一萬個列表,那麼你只能把上面的邏輯定義成函數 def map_test(array): ret=[] for i in array: ret.append(i**2) return ret print(map_test(array)) #若是咱們的需求變了,不是把列表中每一個元素都平方,還有加1,減一,那麼能夠這樣 def add_num(x): return x+1 def map_test(func,array): ret=[] for i in array: ret.append(func(i)) return ret print(map_test(add_num,array)) #可使用匿名函數 print(map_test(lambda x:x-1,array)) #上面就是map函數的功能,map獲得的結果是可迭代對象 print(map(lambda x:x-1,range(5)))
from functools import reduce #合併,得一個合併的結果 array_test=[1,2,3,4,5,6,7] array=range(100) #報錯啊,res沒有指定初始值 def reduce_test(func,array): l=list(array) for i in l: res=func(res,i) return res # print(reduce_test(lambda x,y:x+y,array)) #能夠從列表左邊彈出第一個值 def reduce_test(func,array): l=list(array) res=l.pop(0) for i in l: res=func(res,i) return res print(reduce_test(lambda x,y:x+y,array)) #咱們應該支持用戶本身傳入初始值 def reduce_test(func,array,init=None): l=list(array) if init is None: res=l.pop(0) else: res=init for i in l: res=func(res,i) return res print(reduce_test(lambda x,y:x+y,array)) print(reduce_test(lambda x,y:x+y,array,50))
movie_people=['alex','wupeiqi','yuanhao','sb_alex','sb_wupeiqi','sb_yuanhao'] def tell_sb(x): return x.startswith('sb') def filter_test(func,array): ret=[] for i in array: if func(i): ret.append(i) return ret print(filter_test(tell_sb,movie_people)) #函數filter,返回可迭代對象 print(filter(lambda x:x.startswith('sb'),movie_people))
#固然了,map,filter,reduce,能夠處理全部數據類型 name_dic=[ {'name':'alex','age':1000}, {'name':'wupeiqi','age':10000}, {'name':'yuanhao','age':9000}, {'name':'linhaifeng','age':18}, ] #利用filter過濾掉千年王八,萬年龜,還有一個九千歲 def func(x): age_list=[1000,10000,9000] return x['age'] not in age_list res=filter(func,name_dic) for i in res: print(i) res=filter(lambda x:x['age'] == 18,name_dic) for i in res: print(i) #reduce用來計算1到100的和 from functools import reduce print(reduce(lambda x,y:x+y,range(100),100)) print(reduce(lambda x,y:x+y,range(1,101))) #用map來處理字符串列表啊,把列表中全部人都變成sb,比方alex_sb name=['alex','wupeiqi','yuanhao'] res=map(lambda x:x+'_sb',name) for i in res: print(i)
擴展閱讀:http://www.cnblogs.com/linhaifeng/articles/6108945.html
參考:http://www.cnblogs.com/linhaifeng/p/7278389.html
Python之路,Day4 - Python基礎4 (new版): http://www.cnblogs.com/alex3714/articles/5765046.html