Python基础(三)深浅拷贝、函数、文件处理、三元运算、递归、冒泡排序
本章內(nèi)容:
- 深淺拷貝
- 函數(shù)(全局與局部變量)
- 內(nèi)置函數(shù)
- 文件處理
- 三元運(yùn)算
- lambda 表達(dá)式
- 遞歸(斐波那契數(shù)列)
- 冒泡排序
| 深淺拷貝 |
一、數(shù)字和字符串
對(duì)于 數(shù)字 和 字符串 而言,賦值、淺拷貝和深拷貝無(wú)意義,因?yàn)槠溆肋h(yuǎn)指向同一個(gè)內(nèi)存地址。
import copy #定義變量 數(shù)字、字符串 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))
二、字典、元祖、列表
對(duì)于字典、元祖、列表 而言,進(jìn)行賦值、淺拷貝和深拷貝時(shí),其內(nèi)存地址的變化是不同的。
1、賦值
創(chuàng)建一個(gè)變量,該變量指向原來(lái)內(nèi)存地址
n1 = {"k1": "nick", "k2": 123, "k3": ["jenny", 666]} n2 = n1
2、淺拷貝
在內(nèi)存中只額外創(chuàng)建第一層數(shù)據(jù)
import copyn1 = {"k1": "nick", "k2": 123, "k3": ["jenny", 666]} n2 = copy.copy(n1)
3、深拷貝
在內(nèi)存中將所有的數(shù)據(jù)重新創(chuàng)建一份(排除最后一層,即:python內(nèi)部對(duì)字符串和數(shù)字的優(yōu)化)
import copyn1 = {"k1": "nick", "k2": 123, "k3": ["jenny", 666]} n2 = copy.deepcopy(n1)
| 函數(shù) |
一、定義和使用
函數(shù)式編程最重要的是增強(qiáng)代碼的重用性和可讀性
def 函數(shù)名(參數(shù)):...函數(shù)體...返回值函數(shù)的定義主要有如下要點(diǎn):
- def:表示函數(shù)的關(guān)鍵字
- 函數(shù)名:函數(shù)的名稱(chēng),日后根據(jù)函數(shù)名調(diào)用函數(shù)
- 函數(shù)體:函數(shù)中進(jìn)行一系列的邏輯計(jì)算
- 參數(shù):為函數(shù)體提供數(shù)據(jù)
- 返回值:當(dāng)函數(shù)執(zhí)行完畢后,可以給調(diào)用者返回?cái)?shù)據(jù)。
1、返回值
def 發(fā)送郵件():發(fā)送郵件的代碼...if 發(fā)送成功:return Trueelse:return Falsewhile True:# 每次執(zhí)行發(fā)送郵件函數(shù),都會(huì)將返回值自動(dòng)賦值給result# 之后,可以根據(jù)result來(lái)寫(xiě)日志,或重發(fā)等操作result = 發(fā)送郵件()if result == False:記錄日志,郵件發(fā)送失敗...2、參數(shù)
函數(shù)的有三中不同的參數(shù):
- 普通參數(shù)
- 默認(rèn)參數(shù)
- 動(dòng)態(tài)參數(shù)
#發(fā)送郵件實(shí)例
def mail(主題,郵件內(nèi)容='test',收件人='630571017@qq.com'):import smtplibfrom email.mime.text import MIMETextfrom email.utils import formataddrmsg = MIMEText(郵件內(nèi)容, 'plain', 'utf-8')msg['From'] = formataddr(["發(fā)件人", '發(fā)件人地址'])msg['To'] = formataddr(["收件人", '630571017@qq.com'])msg['Subject'] = 主題server = smtplib.SMTP("smtp.126.com", 25)server.login("登錄郵箱賬號(hào)", "郵箱密碼")server.sendmail('發(fā)件郵箱地址賬號(hào)', [收件人地址, ], msg.as_string())server.quit()mail('我是主題',收件人='630571017@qq.com',郵件內(nèi)容='郵件內(nèi)容') mail(主題='我是主題',) 發(fā)送郵件實(shí)例3、全局與局部變量
全局變量在函數(shù)里可以隨便調(diào)用,但要修改就必須用 global 聲明
############### 全 局 與 局 部 變 量 ############## #全局變量 P = 'nick'def name():global P #聲明修改全局變量P = 'jenny' #局部變量print(P)def name2():print(P)name() name2()?
| 內(nèi)置函數(shù) |
###### 求絕對(duì)值 ####### a = abs(-95) print(a)###### 只有一個(gè)為假就為假 ######## a = all([True,True,False]) print(a)###### 只有一個(gè)為真就為真 ######## a = any([False,True,False]) print(a)####### 返回一個(gè)可打印的對(duì)象字符串方式表示 ######## a = ascii('0x\10000') b = ascii('b\x19') print(a,b)######### 將整數(shù)轉(zhuǎn)換為二進(jìn)制字符串 ############ a = bin(95) print(a)######### 將一個(gè)數(shù)字轉(zhuǎn)化為8進(jìn)制 ############## a = oct(95) print(a)######### 將一個(gè)數(shù)字轉(zhuǎn)化為10進(jìn)制 ############# a = int(95) print(a)######### 將整數(shù)轉(zhuǎn)換為16進(jìn)制字符串 ########## a = hex(95) print(a)######### 轉(zhuǎn)換為布爾類(lèi)型 ########### a = bool('') print(a)######### 轉(zhuǎn)換為bytes ######## a = bytes('索寧',encoding='utf-8') print(a)######## chr 返回一個(gè)字符串,其ASCII碼是一個(gè)整型.比如chr(97)返回字符串'a'。參數(shù)i的范圍在0-255之間。 ####### a = chr(88) print(a)######## ord 參數(shù)是一個(gè)ascii字符,返回值是對(duì)應(yīng)的十進(jìn)制整數(shù) ####### a = ord('X') print(a)######## 創(chuàng)建數(shù)據(jù)字典 ######## dict({'one': 2, 'two': 3}) dict(zip(('one', 'two'), (2, 3))) dict([['two', 3], ['one', 2]]) dict(one=2, two=3)###### dir 列出某個(gè)類(lèi)型的所有可用方法 ######## a = dir(list) print(a)###### help 查看幫助文檔 ######### help(list)####### 分別取商和余數(shù) ###### a = divmod(9,5) print(a)##### 計(jì)算表達(dá)式的值 ##### a = eval('1+2*2') print(a)###### exec 用來(lái)執(zhí)行儲(chǔ)存在字符串或文件中的Python語(yǔ)句 ###### exec(print("Hi,girl.")) exec("print(\"hello, world\")")####### filter 過(guò)濾 ####### li = [1,2,3,4,5,6] a = filter(lambda x:x>3,li) for i in a:print(i)##### float 浮點(diǎn)型 ##### a = float(1) print(a)###### 判斷對(duì)象是不是屬于int實(shí)例 ######### a = 5 b = isinstance(a,int) print(b)######## globals 返回全局變量 ######## ######## locals 返回當(dāng)前局部變量 ###### name = 'nick' def hi():a = 1print(locals()) hi() print(globals())########## map 遍歷序列,對(duì)序列中每個(gè)元素進(jìn)行操作,最終獲取新的序列。 ########## li = [11,22,33] def func1(arg):return arg + 1 #這里乘除都可以 new_list = map(func1,li) #這里map調(diào)用函數(shù),函數(shù)的規(guī)則你可以自己指定,你函數(shù)定義成什么他就做什么操作! 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 隊(duì)集合排序 ######## char=['索',"123", "1", "25", "65","679999999999", "a","B","nick","c" ,"A", "_", "?",'a錢(qián)','孫','李',"余", '佘',"佗", "?", "銥", "啊啊啊啊"] new_chat = sorted(char) print(new_chat) for i in new_chat:print(bytes(i, encoding='utf-8'))######## sum 求和的內(nèi)容 ######## a = sum([1,2,3,4,5]) print(a) a = sum(range(6)) print(a)######## __import__ 通過(guò)字符串的形式,導(dǎo)入模塊 ######## # 通過(guò)字符串的形式,導(dǎo)入模塊。起個(gè)別名ccas comm = input("Please:") ccas = __import__(comm) ccas.f1() # 需要做拼接時(shí)后加 fromlist=True m = __import__("lib."+comm, fromlist=True)
?
| 文件處理 |
open函數(shù),該函數(shù)用于文件處理
一、打開(kāi)文件
打開(kāi)文件時(shí),需要指定文件路徑和以何等方式打開(kāi)文件,打開(kāi)后,即可獲取該文件句柄,日后通過(guò)此文件句柄對(duì)該文件操作。
打開(kāi)文件的模式有:
- r ,只讀模式【默認(rèn)】
- w,只寫(xiě)模式【不可讀;不存在則創(chuàng)建;存在則清空內(nèi)容】
- x, 只寫(xiě)模式【不可讀;不存在則創(chuàng)建,存在則報(bào)錯(cuò)】
- a, 追加模式【不可讀;不存在則創(chuàng)建;存在則只追加內(nèi)容】
"+" 表示可以同時(shí)讀寫(xiě)某個(gè)文件
- r+, 讀寫(xiě)【可讀,可寫(xiě)】
- w+,寫(xiě)讀【可讀,可寫(xiě)】
- x+ ,寫(xiě)讀【可讀,可寫(xiě)】
- a+, 寫(xiě)讀【可讀,可寫(xiě)】
?"b"表示以字節(jié)的方式操作
- rb ?或 r+b
- wb 或 w+b
- xb?或 w+b
- ab?或 a+b
?注:以b方式打開(kāi)時(shí),讀取到的內(nèi)容是字節(jié)類(lèi)型,寫(xiě)入時(shí)也需要提供字節(jié)類(lèi)型
二、操作
####### r 讀 ####### f = open('test.log','r',encoding='utf-8') a = f.read() print(a)###### w 寫(xiě)(會(huì)先清空!!!) ###### f = open('test.log','w',encoding='utf-8') a = f.write('car.\n索寧') print(a) #返回字符####### a 追加(指針會(huì)先移動(dòng)到最后) ######## f = open('test.log','a',encoding='utf-8') a = f.write('girl\n索寧') print(a) #返回字符####### 讀寫(xiě) r+ ######## f = open('test.log','r+',encoding='utf-8') a = f.read() print(a) f.write('nick')##### 寫(xiě)讀 w+(會(huì)先清空!!!) ###### f = open('test.log','w+',encoding='utf-8') a = f.read() print(a) f.write('jenny')######## 寫(xiě)讀 a+(指針先移到最后) ######### f = open('test.log','a+',encoding='utf-8') f.seek(0) #指針位置調(diào)為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')##### 關(guān)閉文件 ###### f.close()##### 內(nèi)存刷到硬盤(pán) ##### f.flush()##### 獲取指針位置 ##### f.tell()##### 指定文件中指針位置 ##### f.seek(0)###### 讀取全部?jī)?nèi)容(如果設(shè)置了size,就讀取size字節(jié)) ###### f.read() f.read(9)###### 讀取一行 ##### f.readline()##### 讀到的每一行內(nèi)容作為列表的一個(gè)元素 ##### f.readlines() class file(object)def close(self): # real signature unknown; restored from __doc__ 關(guān)閉文件"""close() -> None or (perhaps) an integer. Close the file.Sets data attribute .closed to True. A closed file cannot be used forfurther I/O operations. close() may be called more than once withouterror. 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__ 刷新文件內(nèi)部緩沖區(qū)""" flush() -> None. Flush the internal I/O buffer. """passdef isatty(self): # real signature unknown; restored from __doc__ 判斷文件是否是同意tty設(shè)備""" isatty() -> true or false. True if the file is connected to a tty device. """return Falsedef next(self): # real signature unknown; restored from __doc__ 獲取下一行數(shù)據(jù),不存在,則報(bào)錯(cuò)""" x.next() -> the next value, or raise StopIteration """passdef read(self, size=None): # real signature unknown; restored from __doc__ 讀取指定字節(jié)數(shù)據(jù)"""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 requestedmay be returned, even if no size parameter was given."""passdef readinto(self): # real signature unknown; restored from __doc__ 讀取到緩沖區(qū),不要用,將被遺棄""" readinto() -> Undocumented. Don't use this; it may go away. """passdef readline(self, size=None): # real signature unknown; restored from __doc__ 僅讀取一行數(shù)據(jù)"""readline([size]) -> next line from the file, as a string.Retain newline. A non-negative size argument limits the maximumnumber of bytes to return (an incomplete line may be returned then).Return an empty string at EOF."""passdef readlines(self, size=None): # real signature unknown; restored from __doc__ 讀取所有數(shù)據(jù),并根據(jù)換行保存值列表"""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 thetotal 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 (moverelative to end of file, usually negative, although many platforms allowseeking 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 causesundefined behavior.Note that not all file objects are seekable."""passdef tell(self): # real signature unknown; restored from __doc__ 獲取當(dāng)前指針位置""" tell() -> current file position, an integer (may be a long integer). """passdef truncate(self, size=None): # real signature unknown; restored from __doc__ 截?cái)鄶?shù)據(jù),僅保留指定之前數(shù)據(jù)"""truncate([size]) -> None. Truncate the file to at most size bytes.Size defaults to the current file position, as returned by tell()."""passdef write(self, p_str): # real signature unknown; restored from __doc__ 寫(xiě)內(nèi)容"""write(str) -> None. Write string str to file.Note that due to buffering, flush() or close() may be needed beforethe file on disk reflects the data written."""passdef writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__ 將一個(gè)字符串列表寫(xiě)入文件"""writelines(sequence_of_strings) -> None. Write the strings to the file.Note that newlines are not added. The sequence can be any iterable objectproducing strings. This is equivalent to calling write() for each string."""passdef xreadlines(self): # real signature unknown; restored from __doc__ 可用于逐行讀取文件,非全部"""xreadlines() -> returns self.For backward compatibility. File objects now include the performanceoptimizations previously implemented in the xreadlines module."""pass 2.x class TextIOWrapper(_TextIOBase):"""Character and line based layer over a BufferedIOBase object, buffer.encoding gives the name of the encoding that the stream will bedecoded or encoded with. It defaults to locale.getpreferredencoding(False).errors determines the strictness of encoding and decoding (seehelp(codecs.Codec) or the documentation for codecs.register) anddefaults 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 isenabled. Lines in the input can end in '\n', '\r', or '\r\n', andthese are translated into '\n' before being returned to thecaller. If it is '', universal newline mode is enabled, but lineendings are returned to the caller untranslated. If it has any ofthe other legal values, input lines are only terminated by the givenstring, and the line ending is returned to the caller untranslated.* On output, if newline is None, any '\n' characters written aretranslated to the system default line separator, os.linesep. Ifnewline is '' or '\n', no translation takes place. If newline is anyof the other legal values, any '\n' characters written are translatedto the given string.If line_buffering is True, a call to flush is implied when a call towrite contains a newline character."""def close(self, *args, **kwargs): # real signature unknown 關(guān)閉文件passdef fileno(self, *args, **kwargs): # real signature unknown 文件描述符 passdef flush(self, *args, **kwargs): # real signature unknown 刷新文件內(nèi)部緩沖區(qū)passdef isatty(self, *args, **kwargs): # real signature unknown 判斷文件是否是同意tty設(shè)備passdef read(self, *args, **kwargs): # real signature unknown 讀取指定字節(jié)數(shù)據(jù)passdef readable(self, *args, **kwargs): # real signature unknown 是否可讀passdef readline(self, *args, **kwargs): # real signature unknown 僅讀取一行數(shù)據(jù)passdef seek(self, *args, **kwargs): # real signature unknown 指定文件中指針位置passdef seekable(self, *args, **kwargs): # real signature unknown 指針是否可操作passdef tell(self, *args, **kwargs): # real signature unknown 獲取指針位置passdef truncate(self, *args, **kwargs): # real signature unknown 截?cái)鄶?shù)據(jù),僅保留指定之前數(shù)據(jù)passdef writable(self, *args, **kwargs): # real signature unknown 是否可寫(xiě)passdef write(self, *args, **kwargs): # real signature unknown 寫(xiě)內(nèi)容passdef __getstate__(self, *args, **kwargs): # real signature unknownpassdef __init__(self, *args, **kwargs): # real signature unknownpass@staticmethod # known case of __new__def __new__(*args, **kwargs): # real signature unknown""" Create and return a new object. See help(type) for accurate signature. """passdef __next__(self, *args, **kwargs): # real signature unknown""" Implement next(self). """passdef __repr__(self, *args, **kwargs): # real signature unknown""" Return repr(self). """passbuffer = 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.x三、管理上下文
為了避免打開(kāi)文件后忘記關(guān)閉,可以通過(guò)管理上下文,即:
with open('log','r') as f:...如此方式,當(dāng)with代碼塊執(zhí)行完畢時(shí),內(nèi)部會(huì)自動(dòng)關(guān)閉并釋放文件資源。
在Python 2.7 及以后,with又支持同時(shí)對(duì)多個(gè)文件的上下文進(jìn)行管理,即:
with open('log1') as obj1, open('log2') as obj2:pass ###### 從一文件挨行讀取并寫(xiě)入二文件 #########with open('test.log','r') as obj1 , open('test1.log','w') as obj2:for line in obj1:obj2.write(line)?
| 三元運(yùn)算 |
三元運(yùn)算(三目運(yùn)算),是對(duì)簡(jiǎn)單的條件語(yǔ)句的縮寫(xiě)。
result = 值1 if 條件 else 值2# 如果條件成立,那么將 “值1” 賦值給result變量,否則,將“值2”賦值給result變量 ########## 三 元 運(yùn) 算 ############ name = "nick" if 1==1 else "jenny" print(name)
| lambda表達(dá)式 |
對(duì)于簡(jiǎn)單的函數(shù),存在一種簡(jiǎn)便的表示方式,即:lambda表達(dá)式
######## 普 通 函 數(shù) ######## # 定義函數(shù)(普通方式) def func(arg):return arg + 1# 執(zhí)行函數(shù) result = func(123)######## lambda 表 達(dá) 式 ######### 定義函數(shù)(lambda表達(dá)式) my_lambda = lambda arg : arg + 1# 執(zhí)行函數(shù) 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)?
| 遞歸 |
?
遞歸算法是一種直接或者間接地調(diào)用自身算法的過(guò)程。在計(jì)算機(jī)編寫(xiě)程序中,遞歸算法對(duì)解決一大類(lèi)問(wèn)題是十分有效的,它往往使算法的描述簡(jiǎn)潔而且易于理解。 ? 遞歸算法解決問(wèn)題的特點(diǎn):- 遞歸就是在過(guò)程或函數(shù)里調(diào)用自身。
- 在使用遞歸策略時(shí),必須有一個(gè)明確的遞歸結(jié)束條件,稱(chēng)為遞歸出口。
- 遞歸算法解題通常顯得很簡(jiǎn)潔,但遞歸算法解題的運(yùn)行效率較低。所以一般不提倡用遞歸算法設(shè)計(jì)程序。
- 在遞歸調(diào)用的過(guò)程當(dāng)中系統(tǒng)為每一層的返回點(diǎn)、局部量等開(kāi)辟了棧來(lái)存儲(chǔ)。遞歸次數(shù)過(guò)多容易造成棧溢出等。所以一般不提倡用遞歸算法設(shè)計(jì)程序。
?
利用函數(shù)編寫(xiě)如下數(shù)列:
斐波那契數(shù)列指的是這樣一個(gè)數(shù)列 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, arg2arg3 = arg1 + arg2print arg3func(arg2, arg3)func(0,1)#寫(xiě)函數(shù),利用遞歸獲取斐波那契數(shù)列中的第 10 個(gè)數(shù) #方法一 def fie(n):if n == 0 or n == 1:return nelse:return (fie(n-1)+fie(n-2)) ret = fie(10) print(ret) #方法二 def num(a,b,n):if n == 10:return aprint(a)c = a + ba = num(b,c,n + 1)return as = num(0,1,1) print(s)
?
| 冒泡排序 |
將一個(gè)不規(guī)則的數(shù)組按從小到大的順序進(jìn)行排序
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] = tempprint(data)print("after sort:",data)?
?
轉(zhuǎn)載于:https://www.cnblogs.com/maskice/p/6493399.html
總結(jié)
以上是生活随笔為你收集整理的Python基础(三)深浅拷贝、函数、文件处理、三元运算、递归、冒泡排序的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: AC日记——凌乱的yyy 洛谷 P180
- 下一篇: U135掘进机截齿适合什么工况?