Python基礎(三)

Python基礎(三)

  • 深淺拷貝

  • 函數(全局與局部變量)

  • 內置函數

  • 文件處理

  • 三元運算

  • lambda 表達式

  • 遞歸(斐波那契數列)

  • 冒泡排序


深淺拷貝

一、數字和字符串

對於 數字 和 字符串 而言,賦值、淺拷貝和深拷貝無意義,因爲其永遠指向同一個內存地址。

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))

932699-20160507173532406-519735924.png

二、字典、元祖、列表

對於字典、元祖、列表 而言,進行賦值、淺拷貝和深拷貝時,其內存地址的變化是不同的。

1、賦值

創建一個變量,該變量指向原來內存地址

n1 = {"k1": "nick", "k2": 123, "k3": ["jenny", 666]}
n2 = n1

932699-20160507174512859-1344693969.png

2、淺拷貝

在內存中只額外創建第一層數據

import copy
   
n1 = {"k1": "nick", "k2": 123, "k3": ["jenny", 666]}
n2 = copy.copy(n1)

932699-20160507174828203-2084274435.png


3、深拷貝

在內存中將所有的數據重新創建一份(排除最後一層,即:python內部對字符串和數字的優化)

import copy
   
n1 = {"k1": "nick", "k2": 123, "k3": ["jenny", 666]}
n2 = copy.deepcopy(n1)

932699-20160507175119046-1102485367.png

函數

一、定義和使用

函數式編程最重要的是增強代碼的重用性和可讀性

def 函數名(參數):
        
    ...
    函數體
    ...
    返回值


函數的定義主要有如下要點:

  • def:表示函數的關鍵字

  • 函數名:函數的名稱,日後根據函數名調用函數

  • 函數體:函數中進行一系列的邏輯計算

  • 參數:爲函數體提供數據

  • 返回值:當函數執行完畢後,可以給調用者返回數據。

1、返回值

def 發送郵件():
        
    發送郵件的代碼...
    
    if 發送成功:
        return True
    else:
        return False
    
    
while True:
        
    # 每次執行發送郵件函數,都會將返回值自動賦值給result
    # 之後,可以根據result來寫日誌,或重發等操作
    
    result = 發送郵件()
    if result == False:
        記錄日誌,郵件發送失敗...

2、參數

函數的有三中不同的參數:

  • 普通參數

  • 默認參數

  • 動態參數

普通參數:

#定義函數
#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')

注:默認參數需要放在參數列表最後

默認參數


動態參數(*args):

def func(*args):
    print args

# 執行方式一
func(11,22,33,55,66)

# 執行方式二
li = [11,22,33,55,66]
func(*li)

動態參數(*args)


動態參數(**kwargs)

def func(**kwargs):
    print kwargs


# 執行方式一
func(name='nick',age=18)

# 執行方式二
li = {'name':'nick', age:18, 'job':'pythoner'}
func(**li)

動態參數(**kwargs)


動態參數(*agrs,**kwagrs)

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',收件人='[email protected]'):
    import smtplib
    from email.mime.text import MIMEText
    from email.utils import formataddr

    msg = MIMEText(郵件內容, 'plain', 'utf-8')
    msg['From'] = formataddr(["發件人", '發件人地址'])
    msg['To'] = formataddr(["收件人", '[email protected]'])
    msg['Subject'] = 主題

    server = smtplib.SMTP("smtp.126.com", 25)
    server.login("登錄郵箱賬號", "郵箱密碼")
    server.sendmail('發件郵箱地址賬號', [收件人地址, ], msg.as_string())
    server.quit()

mail('我是主題',收件人='[email protected]',郵件內容='郵件內容')
mail(主題='我是主題',)

發送郵件實例


3、全局與局部變量

全局變量在函數裏可以隨便調用,但要修改就必須用 global 聲明

############### 全 局 與 局 部 變 量 ##############
#全局變量
P = 'nick'
 
def name():
    global P        #聲明修改全局變量
    P = 'jenny'     #局部變量
    print(P)
 
def name2():
    print(P)
 
name()
name2()



內置函數

932699-20160513225624265-840032456.png


###### 求絕對值 #######
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)


文件處理

open函數,該函數用於文件處理
一、打開文件

文件句柄 = open('文件路徑', '模式')

打開文件時,需要指定文件路徑和以何等方式打開文件,打開後,即可獲取該文件句柄,日後通過此文件句柄對該文件操作。

打開文件的模式有:

  • r ,只讀模式【默認】

  • w,只寫模式【不可讀;不存在則創建;存在則清空內容】

  • x, 只寫模式【不可讀;不存在則創建,存在則報錯】

  • a, 追加模式【不可讀;不存在則創建;存在則只追加內容】

"+" 表示可以同時讀寫某個文件

  • r+, 讀寫【可讀,可寫】

  • w+,寫讀【可讀,可寫】

  • x+ ,寫讀【可讀,可寫】

  • a+, 寫讀【可讀,可寫】

 "b"表示以字節的方式操作

  • rb  或 r+b

  • wb 或 w+b

  • xb 或 w+b

  • ab 或 a+b

 注:以b方式打開時,讀取到的內容是字節類型,寫入時也需要提供字節類型

二、操作

####### 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

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 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.x


三、管理上下文

爲了避免打開文件後忘記關閉,可以通過管理上下文,即:

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)

932699-20160512233333624-2039928138.png

#寫函數,利用遞歸獲取斐波那契數列中的第 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)


冒泡排序

932699-20160512223648155-1295794741.png


將一個不規則的數組按從小到大的順序進行排序

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)


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章