python第三周學習內容
1.集合:
集合的創建:
list_1 = set([1,2,3,4,5])
list_2 = set([2,3,44,7,8])
集合的特性:集合是無序的,集合可以去掉重復的元素
集合的操作:
求交集:
print(list_1.intersection(list_2)) #{2,3} print(list_l & list_2) #求交集,{2,3}
求並集:
print(list_1.union(list_2)) #{1,2,3,4,5,7,8,44} print(list_l | list_2) #求並集,{1,2,3,4,5,7,8,44}
求差集:
print(list_1.defference(list_2)) #in list_1 but not in list_2,{1,4,5} print(list_l - list_2) #求差集,in list_1 but not in list_2:{1,4,5}
判斷子集:
print(list_1.issubset(list_2)) #list_1是否是list_2的子集,None
判斷父集:
print(list_1.issuperset(list_2)) #list_1是否是list_2的父集,None
對稱差集:
print(list_l.symmetric_difference(list_2)) #對稱差集,並集裏面去掉交集,{1,4,5,7,8,44}
print(list_l ^ list_2) #對稱差集,並集裏面去掉交集
判斷交集:
print(lsit_1.isdijoint(list_2)) #Yes
增加:
lsit_3 = set([1,2,3,4]) #單個增加: list_3.add(5) #多個增加: list_3.update([6,7,8,9])
刪除:
刪除:list_3.remove(1) print(list_3.pop()) #隨機刪除
求集合的長度:
print(len(list_3))
2.文件
文件的創建:
f = open("yesterday","w",encoding="utf-8") ‘‘‘ #with語句,為了避免打開文件後忘記關閉,可以通過管理上下文,即: with open("log","r") as f: pass #python2.7之後,with有支持同時對多個文件的上下文進行管理,即: with open("log1") as obj1,open("log2") as obj2: psss ‘‘‘ #開發規範:一行不得超過八十個字符 with open("yesterday2","r",encoding="GB18030") as f, open("yesterday","r",encoding="GB18030") as f2: for line in f: print(line.strip())
文件的操作:
讀:
f = open("yesterday","r",encoding="utf-8")#不可寫 data = f.read() print(data) #輸出文件的內容 list = f.readlines() ‘‘‘ #將硬盤中的數據全部讀入內存中形成一個列表,並且自動添加了換行符. [‘我愛北京天安門,\n‘, ‘天安門上太陽升\n‘, ‘我愛北京天安門\n‘] ‘‘‘ print(f.readline()) #一行一行地讀 #循環讀: for line in f: print(line)
寫:
f = open("yesterday","w",encoding="utf-8") #不可讀,每運行一次就會創建一個新的文件覆蓋掉原來的文件 f.write("sladjla")
追加:
f = open("yesterday","a",encoding="utf-8")#不可讀 f.write("sldad")
句柄位置操作:
print(f.tell()) #打印句柄位置 f.seek(5) #使句柄回到某個位置 print(f.encoding) #打印文件的編碼 print(f.fileno()) #返回文件編號 print(f.name) #打印文件名字 print(f.isatty()) #判斷是否為終端設備 True、False print(f.seekable()) #判斷句柄是否可移 True、False print(f.readable()) #判斷文件是否可讀 True、False
刷新:
f.flush()#刷新,將內存中的內容一次性刷入硬盤中 import sys,time for i in range(50): sys.stdout.write("#") sys.stdout.flush() time.sleep(0.1)
讀寫、寫讀、追加的、二進制讀寫:
f = open("yesterday2","r+",encoding="GB18030")#讀寫模式,不會清空原文件 f = open("yesterday2","w+",encoding="GB18030")#寫讀模式,會清空原文件 f = open("yesterday2","a+",encoding = "GB18030")#追加讀 f = open("yesterday2","rb或者wb") #二進制文件 print(f.readline()) print(f.readline()) print(f.readline()) print(f.tell()) f.write("\n------diao------") #只能添加在末尾 print(f.readline()) #文件操作的二進制讀寫 f = open("yesterday2","rb") print(f.readline())#b‘\r\n‘ f = open("yesterday2","wb") f.write("hello binary".encode())#只能寫入二進制格式 ‘‘‘ "U"表示在讀取時,可以將\r \n \r\n自動轉換為\n(與r或r+模式同時使用) > rU > r+U ‘‘‘
文件修改:
f = open("yesterday","r",encoding="GB18030") f_new = open("yesterday3","w",encoding="GB18030") for line in f: if "poj" in line: line = line.replace("poj","急急急急急急") f_new.write(line) f.close() f_new.close()
3.字符編碼與轉換:
GBK--decode-->unicode【中間站】--encode-->utf-8
utf-8--decode-->unicode【中間站】--encode-->GBk
GBK轉換為utf-8流程:
1.首先通過編碼【decode】轉換為Unicode編碼
2.然後通過解碼【encode】轉換為utf-8編碼
utf-8轉換為GBK流程:
1.首先通過編碼【decode】轉換為Unicode編碼
2.然後通過解碼【encode】轉換為utf-8編碼
utf-8是Unicode編碼的擴展集,故在utf-8程序中,Unicode格式可以直接打印
但是GBK編碼不能在Unicode程序中直接打印,即使Unicode兼容GBK編碼
在python2中解釋器默認是ASCII碼
python3中解釋器默認是unicode編碼
在python3中進行轉碼、編碼會自動轉成二進制類型
s = "你好" s_gbk = s.encode("gbk") print(s_gbk)#b‘\xc4\xe3\xba\xc3‘ print(s.encode())#b‘\xe4\xbd\xa0\xe5\xa5\xbd‘ gbk_to_utf8 = s_gbk.decode("gbk").encode("utf-8") print(gbk_to_utf8)#b‘\xe4\xbd\xa0\xe5\xa5\xbd‘ s = "你哈" print(s.encode("gbk")) #b‘\xc4\xe3\xb9\xfe‘,因為解釋器默認是Unicode編碼 print(s.encode("utf-8")) #b‘\xe4\xbd\xa0\xe5\x93\x88‘ print(s.encode("utf- 8").decode("utf8").encode("gb2312").decode("gb2312"))#你哈
4.函數與函數式編程:
編程方法:
1.面向對象:華山派----》類----》class
2.面向過程:少林派----》過程----》def
3.函數式編程:逍遙派----》函數-----》def
函數定義:
函數式邏輯結構化和過化的一種編程方法
python中函數定義的方法:
def text(x): "The function definition" x += 1 return x ‘‘‘‘ def:定義函數中的關鍵字 text:函數名 ():內可定義形參 "":文檔描述(非必要,但是強烈建議為你的函數添加描述信息) x += 1:泛指代碼或程序處理器 return:定義返回值 ‘‘‘‘
使用函數的優點:
1.避免了大量代碼的重復使用
2.保持一致性:修改函數中的代碼,在所有使用函數的地方都會改變
3.可擴展性(一致性)
import time def logger(): time_format = "%Y=%m-%d %X" time_current = time.strftime(time_format) with open("hahaha","a+",encoding="utf-8") as f: f.write("%send action\n"%time_current) def text1(): print("in the tex1") logger() def text2(): print("in the tex2") logger() def text3(): print("in the tex3") logger() text1() text2() text3()
函數和過程:
過程定義:過程就是簡單沒有返回值的函數
總結:一個函數/過程沒有使用return顯性的定義返回值時,python解釋器會隱式返回None,所以在python中即便式過程也可以算作是函數
#函數: def func1(): "testing1" print("in the func1") return 0 #過程: def func2(): "testing2" print("in the func2") x = func1() print("from func1 return is %s "%x) #from func1 return is 0 y = func2() print("from func2 return is %s"%y) #from func2 return is None #當一個函數/過程沒有使用return顯性的定義返回值時,python解釋器會隱式返回None, #所以在python中即便是過程也可以算作函數
函數返回值:
返回值數=0,返回None
返回值數=1,返回object
返回值數>1,返回tuple
def text1(): print("in the text1") ‘‘‘ return 0 #結束函數,並返回一個值 print("text end") #不會執行 ‘‘‘ def text2(): print("in the text2") return 0 def text3(): print("in the text3") return 1,"hello",["alex","wupeiqi"],{"name":"alex"} x = text1() y = text2() z = text3() print(type(x),x) #<class ‘NoneType‘> None print(type(y),y) #<class ‘int‘> 0 print(type(z),z) #<class ‘tuple‘> (1, ‘hello‘, [‘alex‘, ‘wupeiqi‘], {‘name‘: ‘alex‘})
函數調用:test()執行,()表示調用test,()可以有參數也可以沒有
參數:
1.形參和實參:
形參:形式參數,不是實際存在的,是虛擬變量。在定義函數和函數體的時候使用形參,目的是在函數調用時接受實參(實參個數、類型因該與形參一一對應)
實參:實際參數,調用函數時傳給函數的參數,可以是常量、變量、表達式、函數傳給形參
區別:形參時虛擬的,不占用內存空間,形參變量只有在被調用時才分配內存單元,實參是一個變量,占用內存空間,數據傳送單向,實參傳給形參,不能形參傳給實參
2.位置參數和關鍵字參數(標準調用:實參和形參位置一一對應;關鍵字調用:位置無需固定)
#標準調用,實參與形參一一對應 def test1(x,y): "x、y是位置參數" print("in the test1:") print("x = %s\ny = %s"%(x,y)) test1(2,1) #實參跟形參必須一一對應 #關鍵字調用,與形參順序無關 def test2(x,y): print("in the test2:") print("x = %s\ny = %s"%(x,y)) test2(y = 1,x = 2) #test2(x = 2,3) error #test2(3,y = 2) OK #因此關鍵字參數不能位於位置參數的前面
3.默認參數:特點:調用函數的時候,默認參數非必須傳遞
def test(x,y=2): print(x) print(y) test(x = 1,y = 3) #OK test(1) #OK #test(y = 3) error #特點:調用函數的時候,默認參數非必須傳遞
4.參數組
def test(*args): print(args) test(1,2,3,4,5) #(1, 2, 3, 4, 5) test(*[1,2,3,5,5]) #args = tuple([1,2,3,5,5]):(1, 2, 3, 5, 5) def test1(x,*args): print(x) print(args) test1(1,2,3,4,5,6,34,3) #1 #*args是接收N個位置參數,轉換成元組的方式 (2, 3, 4, 5, 6, 34, 3) #**kwargs:是就收N個關鍵字參數,轉換成字典的方式;傳遞字典 def test2(**kwargs): print(kwargs) test2(name = "alex",age = 22,sex = "N") #{‘name‘: ‘alex‘, ‘age‘: 22, ‘sex‘: ‘N‘} def test3(name,*args,**kwargs): print("the information of %s:"%name) print(kwargs) print("%s like the numbers:%s"%(name,args)) test3("alex",3,7,21,age = 19,sex = "m") #def test4(name,**kwargs,age=18) error,默認參數必須放在參數組的前面 #def test4(name,age=18,**kwargs) OK
註意:1.關鍵字參數必須位於位置參數的後面 2.默認參數必須放在參數組的前面
前向引用:
函數action體內嵌套某一函數logger,該logger的聲明必須早於action哈桑農戶的調用,否則報錯
全局變量與局部變量:
在子程序中定義的變量稱為局部變量,在程序一開始定義的變量稱為全局變量。
全局變量作用域是整個程序,局部變量作用域是定義該變量的子程序
當全局變量與局部變量沖突時:
在定義局部變量的子程序內,局部變量會屏蔽掉全局變量,在其他地方全部變量起作用
school = "Oldboy edu" #全局變量 def change_name(name): "這個函數就是其內部即局部變量的作用域" global school #將school改為全局變量 school = "mage linux" print("school:",school) print("before change:",name) name = "Alex li" print("after change:",name) name = "alex" change_name(name) print(name)#alex print("shcool:",school)#shcool: mage linux 一般來說,我們不應該在函數內部將局部變量改為全局變量 因為這樣在無數次調用這個函數後,我們很難知道實在哪兒將變量修改了 故我們不應該使用這種方法 def change_name(): global name name = "alex" change_name() print(name) #附註:列表、字典是可以在函數中修改的
高階函數:
變量可以指向函數,函數的參數能接收變量,那麽一個函數就可以接收另一個函數作為參數,這種函數就叫高階函數
def abs(x): if x>=0: return x else: return -x def add(a,b,f): return f(a)+f(b) print(add(3,-6,abs)) #9
遞歸:
定義:如果一個函數在內部調用自己本身,這個函數就是遞歸函數
特性:
1.必須有一個明確的結束條件
2.每次進入更深一層循環時,問題規模相比上次遞歸有所減少
3.遞歸效率不高,遞歸層次過多時回導致棧溢出
def cal(n):
print(n) if int(n/2)>0: return cal(int(n/2)) print("---->",n) cal(10)
python第三周學習內容