本章內容:python
深淺拷貝 |
1、數字和字符串算法
對於 數字 和 字符串 而言,賦值、淺拷貝和深拷貝無心義,由於其永遠指向同一個內存地址。編程
import copy #定義變量 數字、字符串 n1 = 123 #n1 = 'nick' print(id(n1)) #賦值 n2 = n1 print(id(n2)) #淺拷貝 n3 = copy.copy(n1) print(id(n3)) #深拷貝 n4 = copy.deepcopy(n1) print(id(n4))
2、字典、元祖、列表數組
對於字典、元祖、列表 而言,進行賦值、淺拷貝和深拷貝時,其內存地址的變化是不一樣的。app
一、賦值less
建立一個變量,該變量指向原來內存地址ide
n1 = {"k1": "nick", "k2": 123, "k3": ["jenny", 666]} n2 = n1
二、淺拷貝函數式編程
在內存中只額外建立第一層數據函數
import copy n1 = {"k1": "nick", "k2": 123, "k3": ["jenny", 666]} n2 = copy.copy(n1)
三、深拷貝優化
在內存中將全部的數據從新建立一份(排除最後一層,即:python內部對字符串和數字的優化)
import copy n1 = {"k1": "nick", "k2": 123, "k3": ["jenny", 666]} n2 = copy.deepcopy(n1)
函數 |
1、定義和使用
函數式編程最重要的是加強代碼的重用性和可讀性
def 函數名(參數): ... 函數體 ... 返回值
函數的定義主要有以下要點:
一、返回值
def 發送郵件(): 發送郵件的代碼... if 發送成功: return True else: return False while True: # 每次執行發送郵件函數,都會將返回值自動賦值給result # 以後,能夠根據result來寫日誌,或重發等操做 result = 發送郵件() if result == False: 記錄日誌,郵件發送失敗...
二、參數
函數的有三中不一樣的參數:
#定義函數 #n 叫作函數 name 的形式參數,簡稱:形參 def name(n): print(n) #執行函數 #'nick' 叫作函數 name 的實際參數,簡稱:實參 name('nick')
def func(name, age = 18): print("%s:%s")%(name,age) # 指定參數 func('nick', 19) # 使用默認參數 func('nick') 注:默認參數須要放在參數列表最後
def func(*args): print args # 執行方式一 func(11,22,33,55,66) # 執行方式二 li = [11,22,33,55,66] func(*li)
def func(**kwargs): print kwargs # 執行方式一 func(name='nick',age=18) # 執行方式二 li = {'name':'nick', age:18, 'job':'pythoner'} func(**li)
def hi(a,*args,**kwargs): print(a,type(a)) print(args,type(args)) print(kwargs,type(kwargs)) hi(11,22,33,k1='nick',k2='jenny')
#發送郵件實例
def mail(主題,郵件內容='test',收件人='630571017@qq.com'): import smtplib from email.mime.text import MIMEText from email.utils import formataddr msg = MIMEText(郵件內容, 'plain', 'utf-8') msg['From'] = formataddr(["發件人", '發件人地址']) msg['To'] = formataddr(["收件人", '630571017@qq.com']) msg['Subject'] = 主題 server = smtplib.SMTP("smtp.126.com", 25) server.login("登陸郵箱帳號", "郵箱密碼") server.sendmail('發件郵箱地址帳號', [收件人地址, ], msg.as_string()) server.quit() mail('我是主題',收件人='630571017@qq.com',郵件內容='郵件內容') mail(主題='我是主題',)
三、全局與局部變量
全局變量在函數裏能夠隨便調用,但要修改就必須用 global 聲明
############### 全 局 與 局 部 變 量 ############## #全局變量 P = 'nick' def name(): global P #聲明修改全局變量 P = 'jenny' #局部變量 print(P) def name2(): print(P) name() name2()
內置函數 |
###### 求絕對值 ####### a = abs(-95) print(a) ###### 只有一個爲假就爲假 ######## a = all([True,True,False]) print(a) ###### 只有一個爲真就爲真 ######## a = any([False,True,False]) print(a) ####### 返回一個可打印的對象字符串方式表示 ######## a = ascii('0x\10000') b = ascii('b\x19') print(a,b) ######### 將整數轉換爲二進制字符串 ############ a = bin(95) print(a) ######### 將一個數字轉化爲8進制 ############## a = oct(95) print(a) ######### 將一個數字轉化爲10進制 ############# a = int(95) print(a) ######### 將整數轉換爲16進制字符串 ########## a = hex(95) print(a) ######### 轉換爲布爾類型 ########### a = bool('') print(a) ######### 轉換爲bytes ######## a = bytes('索寧',encoding='utf-8') print(a) ######## chr 返回一個字符串,其ASCII碼是一個整型.好比chr(97)返回字符串'a'。參數i的範圍在0-255之間。 ####### a = chr(88) print(a) ######## ord 參數是一個ascii字符,返回值是對應的十進制整數 ####### a = ord('X') print(a) ######## 建立數據字典 ######## dict({'one': 2, 'two': 3}) dict(zip(('one', 'two'), (2, 3))) dict([['two', 3], ['one', 2]]) dict(one=2, two=3) ###### dir 列出某個類型的全部可用方法 ######## a = dir(list) print(a) ###### help 查看幫助文檔 ######### help(list) ####### 分別取商和餘數 ###### a = divmod(9,5) print(a) ##### 計算表達式的值 ##### a = eval('1+2*2') print(a) ###### exec 用來執行儲存在字符串或文件中的Python語句 ###### exec(print("Hi,girl.")) exec("print(\"hello, world\")") ####### filter 過濾 ####### li = [1,2,3,4,5,6] a = filter(lambda x:x>3,li) for i in a:print(i) ##### float 浮點型 ##### a = float(1) print(a) ###### 判斷對象是否是屬於int實例 ######### a = 5 b = isinstance(a,int) print(b) ######## globals 返回全局變量 ######## ######## locals 返回當前局部變量 ###### name = 'nick' def hi(): a = 1 print(locals()) hi() print(globals()) ########## map 遍歷序列,對序列中每一個元素進行操做,最終獲取新的序列。 ########## li = [11,22,33] def func1(arg): return arg + 1 #這裏乘除均可以 new_list = map(func1,li) #這裏map調用函數,函數的規則你能夠本身指定,你函數定義成什麼他就作什麼操做! for i in new_list:print(i) ###### max 返回集合中的最大值 ###### ###### min 返回集合中的最小值 ###### a = [1,2,3,4,5] s = max(a) print(s) n = min(a) print(n) ####### pow 返回x的y次冪 ######## a = pow(2,10) print(a) a = pow(2,10,100) #等於2**10%100,取模 print(a) ######## round 四捨五入 ######## a = round(9.5) print(a) ######## sorted 隊集合排序 ######## char=['索',"123", "1", "25", "65","679999999999", "a","B","nick","c" ,"A", "_", "ᒲ",'a錢','孫','李',"餘", '佘',"佗", "㽙", "銥", "啊啊啊啊"] new_chat = sorted(char) print(new_chat) for i in new_chat: print(bytes(i, encoding='utf-8')) ######## sum 求和的內容 ######## a = sum([1,2,3,4,5]) print(a) a = sum(range(6)) print(a) ######## __import__ 經過字符串的形式,導入模塊 ######## # 經過字符串的形式,導入模塊。起個別名ccas comm = input("Please:") ccas = __import__(comm) ccas.f1() # 須要作拼接時後加 fromlist=True m = __import__("lib."+comm, fromlist=True)
lt(a, b) 至關於 a < b le(a,b) 至關於 a <= b eq(a,b) 至關於 a == b ne(a,b) 至關於 a != b gt(a,b) 至關於 a > b ge(a, b)至關於 a>= b
zip函數接受任意多個(包括0個和1個)序列做爲參數,返回一個tuple列表。具體意思很差用文字來表述,直接看示例: 1.示例1: 複製代碼 x = [1, 2, 3] y = [4, 5, 6] z = [7, 8, 9] xyz = zip(x, y, z) print xyz 複製代碼 運行的結果是: [(1, 4, 7), (2, 5, 8), (3, 6, 9)] 從這個結果能夠看出zip函數的基本運做方式。 2.示例2: x = [1, 2, 3] y = [4, 5, 6, 7] xy = zip(x, y) print xy 運行的結果是: [(1, 4), (2, 5), (3, 6)] 從這個結果能夠看出zip函數的長度處理方式。 3.示例3: x = [1, 2, 3] x = zip(x) print x 運行的結果是: [(1,), (2,), (3,)] 從這個結果能夠看出zip函數在只有一個參數時運做的方式。 4.示例4: x = zip() print x 運行的結果是: [] 從這個結果能夠看出zip函數在沒有參數時運做的方式。 5.示例5: 複製代碼 x = [1, 2, 3] y = [4, 5, 6] z = [7, 8, 9] xyz = zip(x, y, z) u = zip(*xyz) print u 複製代碼 運行的結果是: [(1, 2, 3), (4, 5, 6), (7, 8, 9)] 通常認爲這是一個unzip的過程,它的運行機制是這樣的: 在運行zip(*xyz)以前,xyz的值是:[(1, 4, 7), (2, 5, 8), (3, 6, 9)] 那麼,zip(*xyz) 等價於 zip((1, 4, 7), (2, 5, 8), (3, 6, 9)) 因此,運行結果是:[(1, 2, 3), (4, 5, 6), (7, 8, 9)] 注:在函數調用中使用*list/tuple的方式表示將list/tuple分開,做爲位置參數傳遞給對應函數(前提是對應函數支持不定個數的位置參數) 6.示例6: x = [1, 2, 3] r = zip(* [x] * 3) print r 運行的結果是: [(1, 1, 1), (2, 2, 2), (3, 3, 3)] 它的運行機制是這樣的: [x]生成一個列表的列表,它只有一個元素x [x] * 3生成一個列表的列表,它有3個元素,[x, x, x] zip(* [x] * 3)的意思就明確了,zip(x, x, x)
文件處理 |
open函數,該函數用於文件處理
1、打開文件
文件句柄 = open('文件路徑', '模式')
打開文件時,須要指定文件路徑和以何等方式打開文件,打開後,便可獲取該文件句柄,往後經過此文件句柄對該文件操做。
打開文件的模式有:
"+" 表示能夠同時讀寫某個文件
"b"表示以字節的方式操做
注:以b方式打開時,讀取到的內容是字節類型,寫入時也須要提供字節類型
2、操做
####### r 讀 ####### f = open('test.log','r',encoding='utf-8') a = f.read() print(a) ###### w 寫(會先清空!!!) ###### f = open('test.log','w',encoding='utf-8') a = f.write('car.\n索寧') print(a) #返回字符 ####### a 追加(指針會先移動到最後) ######## f = open('test.log','a',encoding='utf-8') a = f.write('girl\n索寧') print(a) #返回字符 ####### 讀寫 r+ ######## f = open('test.log','r+',encoding='utf-8') a = f.read() print(a) f.write('nick') ##### 寫讀 w+(會先清空!!!) ###### f = open('test.log','w+',encoding='utf-8') a = f.read() print(a) f.write('jenny') ######## 寫讀 a+(指針先移到最後) ######### f = open('test.log','a+',encoding='utf-8') f.seek(0) #指針位置調爲0 a = f.read() print(a) b = f.write('nick') print(b) ####### rb ######### f = open('test.log','rb') a = f.read() print(str(a,encoding='utf-8')) # ######## ab ######### f = open('test.log','ab') f.write(bytes('索寧\ncar',encoding='utf-8')) f.write(b'jenny') ##### 關閉文件 ###### f.close() ##### 內存刷到硬盤 ##### f.flush() ##### 獲取指針位置 ##### f.tell() ##### 指定文件中指針位置 ##### f.seek(0) ###### 讀取所有內容(若是設置了size,就讀取size字節) ###### f.read() f.read(9) ###### 讀取一行 ##### f.readline() ##### 讀到的每一行內容做爲列表的一個元素 ##### f.readlines()
class file(object) def close(self): # real signature unknown; restored from __doc__ 關閉文件 """ close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for further I/O operations. close() may be called more than once without error. Some kinds of file objects (for example, opened by popen()) may return an exit status upon closing. """ def fileno(self): # real signature unknown; restored from __doc__ 文件描述符 """ fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read(). """ return 0 def flush(self): # real signature unknown; restored from __doc__ 刷新文件內部緩衝區 """ flush() -> None. Flush the internal I/O buffer. """ pass def isatty(self): # real signature unknown; restored from __doc__ 判斷文件是不是贊成tty設備 """ isatty() -> true or false. True if the file is connected to a tty device. """ return False def next(self): # real signature unknown; restored from __doc__ 獲取下一行數據,不存在,則報錯 """ x.next() -> the next value, or raise StopIteration """ pass def read(self, size=None): # real signature unknown; restored from __doc__ 讀取指定字節數據 """ read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. """ pass def readinto(self): # real signature unknown; restored from __doc__ 讀取到緩衝區,不要用,將被遺棄 """ readinto() -> Undocumented. Don't use this; it may go away. """ pass def readline(self, size=None): # real signature unknown; restored from __doc__ 僅讀取一行數據 """ readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. """ pass def readlines(self, size=None): # real signature unknown; restored from __doc__ 讀取全部數據,並根據換行保存值列表 """ readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned. """ return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__ 指定文件中指針位置 """ seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to (offset from start of file, offset should be >= 0); other values are 1 (move relative to current position, positive or negative), and 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are seekable. """ pass def tell(self): # real signature unknown; restored from __doc__ 獲取當前指針位置 """ tell() -> current file position, an integer (may be a long integer). """ pass def truncate(self, size=None): # real signature unknown; restored from __doc__ 截斷數據,僅保留指定以前數據 """ truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell(). """ pass def write(self, p_str): # real signature unknown; restored from __doc__ 寫內容 """ write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written. """ pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__ 將一個字符串列表寫入文件 """ writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string. """ pass def xreadlines(self): # real signature unknown; restored from __doc__ 可用於逐行讀取文件,非所有 """ xreadlines() -> returns self. For backward compatibility. File objects now include the performance optimizations previously implemented in the xreadlines module. """ pass
class TextIOWrapper(_TextIOBase): """ Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be decoded or encoded with. It defaults to locale.getpreferredencoding(False). errors determines the strictness of encoding and decoding (see help(codecs.Codec) or the documentation for codecs.register) and defaults to "strict". newline controls how line endings are handled. It can be None, '', '\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newline mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. If line_buffering is True, a call to flush is implied when a call to write contains a newline character. """ def close(self, *args, **kwargs): # real signature unknown 關閉文件 pass def fileno(self, *args, **kwargs): # real signature unknown 文件描述符 pass def flush(self, *args, **kwargs): # real signature unknown 刷新文件內部緩衝區 pass def isatty(self, *args, **kwargs): # real signature unknown 判斷文件是不是贊成tty設備 pass def read(self, *args, **kwargs): # real signature unknown 讀取指定字節數據 pass def readable(self, *args, **kwargs): # real signature unknown 是否可讀 pass def readline(self, *args, **kwargs): # real signature unknown 僅讀取一行數據 pass def seek(self, *args, **kwargs): # real signature unknown 指定文件中指針位置 pass def seekable(self, *args, **kwargs): # real signature unknown 指針是否可操做 pass def tell(self, *args, **kwargs): # real signature unknown 獲取指針位置 pass def truncate(self, *args, **kwargs): # real signature unknown 截斷數據,僅保留指定以前數據 pass def writable(self, *args, **kwargs): # real signature unknown 是否可寫 pass def write(self, *args, **kwargs): # real signature unknown 寫內容 pass def __getstate__(self, *args, **kwargs): # real signature unknown pass def __init__(self, *args, **kwargs): # real signature unknown pass @staticmethod # known case of __new__ def __new__(*args, **kwargs): # real signature unknown """ Create and return a new object. See help(type) for accurate signature. """ pass def __next__(self, *args, **kwargs): # real signature unknown """ Implement next(self). """ pass def __repr__(self, *args, **kwargs): # real signature unknown """ Return repr(self). """ pass buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default
3、管理上下文
爲了不打開文件後忘記關閉,能夠經過管理上下文,即:
with open('log','r') as f: ...
如此方式,當with代碼塊執行完畢時,內部會自動關閉並釋放文件資源。
在Python 2.7 及之後,with又支持同時對多個文件的上下文進行管理,即:
with open('log1') as obj1, open('log2') as obj2: pass
###### 從一文件挨行讀取並寫入二文件 ######### with open('test.log','r') as obj1 , open('test1.log','w') as obj2: for line in obj1: obj2.write(line)
三元運算 |
三元運算(三目運算),是對簡單的條件語句的縮寫。
result = 值1 if 條件 else 值2 # 若是條件成立,那麼將 「值1」 賦值給result變量,不然,將「值2」賦值給result變量
########## 三 元 運 算 ############ name = "nick" if 1==1 else "jenny" print(name)
lambda表達式 |
對於簡單的函數,存在一種簡便的表示方式,即:lambda表達式
######## 普 通 函 數 ######## # 定義函數(普通方式) def func(arg): return arg + 1 # 執行函數 result = func(123) ######## lambda 表 達 式 ######## # 定義函數(lambda表達式) my_lambda = lambda arg : arg + 1 # 執行函數 result = my_lambda(123)
##### 列表從新判斷操做排序 ##### li = [11,15,9,21,1,2,68,95] s = sorted(map(lambda x:x if x > 11 else x * 9,li)) print(s) ###################### ret = sorted(filter(lambda x:x>22, [55,11,22,33,])) print(ret)
遞歸 |
def fact_iter(product,count,max): if count > max: return product return fact_iter(product * count, count+1, max) print(fact_iter(1,1,5)) print(fact_iter(1,2,5)) print(fact_iter(2,3,5)) print(fact_iter(6,4,5)) print(fact_iter(24,5,5)) print(fact_iter(120,6,5))
利用函數編寫以下數列:
斐波那契數列指的是這樣一個數列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233,377,610,987,1597,2584,4181,6765,10946,17711,28657,46368...
def func(arg1,arg2): if arg1 == 0: print arg1, arg2 arg3 = arg1 + arg2 print arg3 func(arg2, arg3) func(0,1)
#寫函數,利用遞歸獲取斐波那契數列中的第 10 個數 #方法一 def fie(n): if n == 0 or n == 1: return n else: return (fie(n-1)+fie(n-2)) ret = fie(10) print(ret) #方法二 def num(a,b,n): if n == 10: return a print(a) c = a + b a = num(b,c,n + 1) return a s = num(0,1,1) print(s)
冒泡排序 |
將一個不規則的數組按從小到大的順序進行排序
data = [10,4,33,21,54,8,11,5,22,2,17,13,3,6,1,] print("before sort:",data) for j in range(1,len(data)): for i in range(len(data) - j): if data[i] > data[i + 1]: temp = data[i] data[i] = data[i + 1] data[i + 1] = temp print(data) print("after sort:",data)