python——內建函數和匿名函數

來源:互聯網
上載者:User

標籤:歸類   方法   class   case   改變   匯入   全域   作檔案   err   

內建函數

接下來,我們就一起來看看python裡的內建函數。截止到python版本3.6.2,現在python一共為我們提供了68個內建函數。它們就是python提供給你直接可以拿來使用的所有函數。這些函數有些我們已經用過了,有些我們還沒用到過,還有一些是被封印了,必須等我們學了新知識才能解開封印的。那今天我們就一起來認識一下python的內建函數。這麼多函數,我們該從何學起呢?

    Built-in Functions    
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
classmethod() getattr() locals() repr() zip()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()  
delattr() hash() memoryview() set()  

 

 

 

範圍相關

基於字典的形式擷取局部變數和全域變數

globals()——擷取全域變數的字典

locals()——擷取執行本方法所在命名空間內的局部變數的字典

其他

 

輸入輸出相關:

input() 輸入

s = input("請輸入內容 : ")  #輸入的內容賦值給s變數print(s)  #輸入什麼列印什麼。資料類型是str
s = input("請輸入內容 : ")  #輸入的內容賦值給s變數print(s)  #輸入什麼列印什麼。資料類型是str

print() 輸出

def print(self, *args, sep=‘ ‘, end=‘\n‘, file=None): # known special case of print    """    print(value, ..., sep=‘ ‘, end=‘\n‘, file=sys.stdout, flush=False)    file:  預設是輸出到螢幕,如果設定為檔案控制代碼,輸出到檔案    sep:   列印多個值之間的分隔字元,預設為空白格    end:   每一次列印的結尾,預設為分行符號    flush: 立即把內容輸出到流檔案,不作緩衝    """
def print(self, *args, sep=‘ ‘, end=‘\n‘, file=None): # known special case of print    """    print(value, ..., sep=‘ ‘, end=‘\n‘, file=sys.stdout, flush=False)    file:  預設是輸出到螢幕,如果設定為檔案控制代碼,輸出到檔案    sep:   列印多個值之間的分隔字元,預設為空白格    end:   每一次列印的結尾,預設為分行符號    flush: 立即把內容輸出到流檔案,不作緩衝    """
f = open(‘tmp_file‘,‘w‘)print(123,456,sep=‘,‘,file = f,flush=True)
f = open(‘tmp_file‘,‘w‘)print(123,456,sep=‘,‘,file = f,flush=True)
import timeimport sysfor i in range(0,101,2):     time.sleep(0.1)     char_num = i//2      #列印多少個#     per_str = ‘%s%% : %s\n‘ % (i, ‘*‘ * char_num) if i == 100 else ‘\r%s%% : %s‘%(i,‘*‘*char_num)     print(per_str,end=‘‘, file=sys.stdout, flush=True)
import timeimport sysfor i in range(0,101,2):     time.sleep(0.1)     char_num = i//2      #列印多少個#     per_str = ‘%s%% : %s\n‘ % (i, ‘*‘ * char_num) if i == 100 else ‘\r%s%% : %s‘%(i,‘*‘*char_num)     print(per_str,end=‘‘, file=sys.stdout, flush=True)

 

資料類型相關:

type(o) 返回變數o的資料類型

 

記憶體相關:

id(o) o是參數,返回一個變數的記憶體位址

hash(o) o是參數,返回一個可hash變數的雜湊值,不可hash的變數被hash之後會報錯。

t = (1,2,3)l = [1,2,3]print(hash(t))  #可hashprint(hash(l))  #會報錯‘‘‘結果:TypeError: unhashable type: ‘list‘‘‘‘
t = (1,2,3)l = [1,2,3]print(hash(t))  #可hashprint(hash(l))  #會報錯‘‘‘結果:TypeError: unhashable type: ‘list‘‘‘‘

hash函數會根據一個內部的演算法對當前可hash變數進行處理,返回一個int數字。

*每一次執行程式,內容相同的變數hash值在這一次執行過程中不會發生改變。

 

檔案操作相關

open()  開啟一個檔案,返回一個檔案操作符(檔案控制代碼)

操作檔案的模式有r,w,a,r+,w+,a+ 共6種,每一種方式都可以用二進位的形式操作(rb,wb,ab,rb+,wb+,ab+)

可以用encoding指定編碼.

 

模組操作相關

__import__匯入一個模組

  import time
import time

 

協助方法

在控制台執行help()進入協助模式。可以隨意輸入變數或者變數的類型。輸入q退出

或者直接執行help(o),o是參數,查看和變數o有關的操作。。。

 

和調用相關

callable(o),o是參數,看這個變數是不是可調用。

如果o是一個函數名,就會返回True

def func():passprint(callable(func))  #參數是函數名,可調用,返回Trueprint(callable(123))   #參數是數字,不可調用,返回False

 

查看參數所屬類型的所有內建方法

dir() 預設查看全域空間內的屬性,也接受一個參數,查看這個參數內的方法或變數

print(dir(list))  #查看列表的內建方法print(dir(int))  #查看整數的內建方法
print(dir(list))  #查看列表的內建方法print(dir(int))  #查看整數的內建方法

 

str類型代碼的執行

http://www.cnblogs.com/Eva-J/articles/7266087.html

 

和數字相關

數字——資料類型相關:bool,int,float,complex

數字——進位轉換相關:bin,oct,hex

數字——數學運算:abs,divmod,min,max,sum,round,pow

 

和資料結構相關

序列——列表和元組相關的:list和tuple

序列——字串相關的:str,format,bytes,bytesarry,memoryview,ord,chr,ascii,repr

序列:reversed,slice

資料集合——字典和集合:dict,set,frozenset

資料集合:len,sorted,enumerate,all,any,zip,filter,map

filter和map:http://www.cnblogs.com/Eva-J/articles/7266192.html

sorted方法:http://www.cnblogs.com/Eva-J/articles/7265992.html

 

匿名函數

匿名函數:為瞭解決那些功能很簡單的需求而設計的一句話函數

#這段代碼def calc(n):    return n**nprint(calc(10)) #換成匿名函數calc = lambda n:n**nprint(calc(10))

上面是我們對calc這個匿名函數的分析,下面給出了一個關於匿名函數格式的說明

函數名 = lambda 參數 :傳回值#參數可以有多個,用逗號隔開#匿名函數不管邏輯多複雜,只能寫一行,且邏輯執行結束後的內容就是傳回值#傳回值和正常的函數一樣可以是任意資料類型

我們可以看出,匿名函數並不是真的不能有名字。

匿名函數的調用和正常的調用也沒有什麼分別。 就是 函數名(參數) 就可以了~~~

練一練:

請把以下函數變成匿名函數def add(x,y):    return x+y

 

上面是匿名函數的函數用法。除此之外,匿名函數也不是浪得虛名,它真的可以匿名。在和其他功能函數合作的時候

l=[3,2,100,999,213,1111,31121,333]print(max(l))dic={‘k1‘:10,‘k2‘:100,‘k3‘:30}print(max(dic))print(dic[max(dic,key=lambda k:dic[k])])
res = map(lambda x:x**2,[1,5,7,4,8])for i in res:    print(i)輸出125491664
res = filter(lambda x:x>10,[5,8,11,9,15])for i in res:    print(i)輸出1115

面試題練一練

現有兩個元組((‘a‘),(‘b‘)),((‘c‘),(‘d‘)),請使用python中匿名函數產生列表[{‘a‘:‘c‘},{‘b‘:‘d‘}]

#答案一test = lambda t1,t2 :[{i:j} for i,j in zip(t1,t2)]print(test(t1,t2))#答案二print(list(map(lambda t:{t[0]:t[1]},zip(t1,t2))))#還可以這樣寫print([{i:j} for i,j in zip(t1,t2)])
#答案一test = lambda t1,t2 :[{i:j} for i,j in zip(t1,t2)]print(test(t1,t2))#答案二print(list(map(lambda t:{t[0]:t[1]},zip(t1,t2))))#還可以這樣寫print([{i:j} for i,j in zip(t1,t2)])

 

 

本章小結

說學習內建函數,不如說整理自己的知識體系。其實整理這些內建函數的過程也是在整理自己的知識體系。

我們講課的時候會歸類:常用或者不常用,主要還是根據情境而言。

一個優秀的程式員就應該是在該用這個方法的時候信手拈來,把每一個內建的函數都用的恰到好處。

要想做到這一點,至少要先瞭解,才能在需要的時候想起,進而將它用在該用的地方。

但是在這裡,我還是以自己的一點經驗之談,把幾個平時工作中相對更常用的方法推薦一下,請務必重點掌握:

其他:input,print,type,hash,open,import,dir

str類型代碼執行:eval,exec

數字:bool,int,float,abs,divmod,min,max,sum,round,pow

序列——列表和元組相關的:list和tuple

序列——字串相關的:str,bytes,repr

序列:reversed,slice

資料集合——字典和集合:dict,set,frozenset

資料集合:len,sorted,enumerate,zip,filter,map

參考文檔:

  https://docs.python.org/3/library/functions.html#object

python——內建函數和匿名函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.