如上圖,本次將挑python的內建函數中常用的簡要示範一下
為了方便看,將同類方法的函數連在一起示範; abs():取絕對值
>>> print(abs(-2345))2345
/# 0,[],”“,(),{},None 這些字元python中會當作布爾值Flase
all():都為真,才為真
#all不接受多個字串作為參數,只能將這些參數放到一個列表(或元祖等)中>>> print(all(0,True,1,['qwe','wer',],'qwe'))Traceback (most recent call last): File "<stdin>", line 1, in <module>TypeError: all() takes exactly one argument (5 given)#因為0被python認為是False,所以整體為False>>> print(all(['qwe','wer',True,0,]))False#改成1後就變成True了,>>> print(all(['qwe','wer',True,1,]))True
any():任一為真,則為真
>>> print(any([None,0,[],(),]))False>>> print(any([None,0,[],(),1,]))True
數字進位轉換:bin(),oct(),int(),hex(),
#初始設定變數>>> ret=520#十進位轉為二進位>>> print(bin(ret))0b1000001000#十進位轉八進位>>> print(oct(ret))0o1010#十進位轉為十進位>>> print(int(ret))520#十進位轉十六進位>>> print(hex(ret))0x208
bool():判斷布爾值
>>> print(bool(0))False>>> print(bool(1))True>>> print(bool(None))False>>> print(bool(""))False>>> print(bool("qwertw"))True
float():將整型數字轉為浮點數型
round(float(),num):將浮點型數字,四捨五入到小數點後指定位元(num)
>>> reg=520>>> float(reg)520.0>>> ret = reg/1314>>> round(ret,4)0.3957>>> print(ret)0.395738203957382
bytes():將字串轉換為位元組,可以用來轉換字元集【重要】
>>> name = "雲端漫步" >>> ret = bytes(name,encoding='gbk')>>> reg = bytes(name,encoding='utf-8')>>> print(ret,reg)b'\xd4\xc6\xb6\xcb\xc2\xfe\xb2\xbd' b'\xe4\xba\x91\xe7\xab\xaf\xe6\xbc\xab\xe6\xad\xa5'
ord():尋找字元在ASCII表中對應的數值
chr():反向尋找數值對應ASCII表代表的字元
>>> asg = "B">>> ord(asg)66>>> chr(ord(asg))'B'
可以藉此實現隨機驗證碼的功能,詳細可點此參考 dir(),help():Python中擷取協助資訊
>>> dir(dir)['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']>>> help(dir)Help on built-in function dir in module builtins:dir(...) dir([object]) -> list of strings ...
divmod():做除法,並將商和餘數以元祖的形勢返回
>>> a = 1314>>> b = 520>>> divmod(a,b)(2, 274)
藉此可以實現一個小案例:(共234條記錄,每頁顯示25條,共需要幾頁)
total = 234per = 25result = divmod(total,per)if result[1] == 0: ret = result[0]else: ret = result[1]print(ret)
enumerate(): 迭代器,以list的形勢返回索引和值
#建立對象來表現a = [ 11,22,4,33,4,[1,2,3,4,]]ret = enumerate(a)print(ret)print(list(ret)) > <enumerate object at 0x0000000000D91480> > [(0, 11), (1, 22), (2, 4), (3, 33), (4, 4), (5, [1, 2, 3, 4])]#或者用for迴圈迭代器來表現for index,value in enumerate(a): print(index,value)
>0 11 >1 22 >2 4 >3 33 >4 4 >5 [1, 2, 3, 4]
eval(): 執行運算式,拿到結果,並有傳回值
ps:eval() arg 1 must be a string, bytes or code object,eval()對參數的類型要去
reg = '1+(2+8)*3'ret = eval(reg)print(ret)
compile(): 將字串轉義成python code
reg = '1+(2+8)*3'ret = compile(reg,'<string>','exec')print(type(ret),ret)
<class 'code'> <code object <module> at 0x00000000006B28A0, file "<string>", line 1>
exec(): 執行python code,但是沒有傳回值
reg = "print(eval('1+(2+8)*3'))"ret = exec(reg)print(ret)
總結:eval(),相當於將 compile() 和exec()兩個函數的方法封裝在了一起,compile負責將字串轉義成python code,exec將轉義的code進行執行,compile更像是在exec外面加了一層裝飾器,並將結合在一起的函數體賦給eval 【重要】filter(): 對可迭代對象進行篩選
ret = [1,2,4,5,5,6,66,78,324,7,4,2,]reg = filter(lambda a:a>6,ret)print(reg,type(reg))print(list(reg))
注意輸出,如果直接列印返回的對象reg,則會給出記憶體位址,再來看看類型,class‘filter’,因此要得到結果就得使用可迭代對象的類 再次建立對象’list(reg)’
filter object at 0x0000000000D29E10> <class 'filter'>[66, 78, 324, 7]
【重要】map(): 對可迭代對象進行操作
ret = [1,2,4,5,5,6,66,78,324,7,4,2,]pjt = map(lambda b:print(b),ret)print(pjt,type(pjt))print(list(pjt))
輸出,類似filter的結果,可自行體悟
<map object at 0x0000000000D29EB8> <class 'map'>1245566678324742[None, None, None, None, None, None, None, None, None, None, None, None]
id():擷取運算式所在記憶體位址
ret = [1,2,4,5,5,6,66,78,324,7,4,2,]reg = id(ret)print(reg)
D:\python\python.exe D:/python/Project-13/tmp/內建.py11665992
isinstance() :判斷是否為某個類的對象,返回True & Flase
age = 25print(isinstance(age,str))print(isinstance(age,int))
len(): 返回字元長度
ps:注意是字元長度,不是位元組長度,一個字母,一個漢字都被分為是一個字元
#int整數類,沒有len方法,因此無法調用,只能以str類建立對象age = '31'name = '詹姆斯'fav = 'MVP'dig = [31,11,12]print(len(age),len(name),len(fav),len(dig))
D:\python\python.exe D:/python/Project-13/tmp/內建.py2 3 3 3
global() 返回當前代碼環境的全域變數,locals() 返回當前代碼環境的局部變數, 返回的是字典類型
name = '詹姆斯'def newinfo(): fav = '總冠軍' age = 31 print('15-16賽季,聯盟最強') print(globals()) print(locals())newinfo()
15-16賽季,聯盟最強{'newinfo': <function newinfo at 0x0000000000D4AEA0>, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x00000000009C7860>, '__spec__': None, 'name': '詹姆斯', '__file__': 'D:/python/Project-13/tmp/內建.py', '__package__': None, '__name__': '__main__', '__builtins__': <module 'builtins' (built-in)>, '__cached__': None, '__doc__': None}{'fav': '總冠軍', 'age': 31}
max() min() sum() :取最大值、最小值、求和
ret = [1,2,4,5,5,6,66,78,324,7,4,2,]print(max(ret),min(ret),sum(ret))
D:\python\python.exe D:/python/Project-13/tmp/內建.py324 1 504
pow(x,y,z): 兩個參數時表示x的y次方 ;三個參數時表示 x**y %z,在為取餘
reg = pow(2,10)ret = pow(2,10,10)print(reg,ret)
D:\python\python.exe D:/python/Project-13/tmp/內建.py1024 4
zip() :接受多個同類型的資料類型,然後‘列’轉‘行’,返回一個元組tuple
a = [23,12,32,34]b = [23,43,127,]c = [654,2,]reg = zip(a,b,c)print(reg,type(reg))print(list(reg))
從輸出中不難看出,以最短的一個序列為準,只匹配最短序列數量的元組元素
D:\python\python.exe D:/python/Project-13/tmp/內建.py<zip object at 0x0000000000D230C8> <class 'zip'>[(23, 23, 654), (12, 43, 2)]
最後介紹一下3.5和2.7的一下區別
# python3.5 可按照字元來遍曆,也可按照位元組for i in "詹姆斯": print(i)a = "詹姆斯"print(a[:3], a[3:6], a[6:9])# python2.7 #只能按照位元組a = "詹姆斯"print a[:3], a[3:6], a[6:9]
D:\python\python.exe D:/python/Project-13/tmp/內建.py詹姆斯詹姆斯 詹姆斯