天天看點

Python-開發之路-内建函數

Python-開發之路-内建函數

如上圖,本次将挑python的内建函數中常用的簡要示範一下

為了友善看,将同類方法的函數連在一起示範;

abs():取絕對值

>>> print(abs(-))

           

/# 0,[],”“,(),{},None 這些字元python中會當作布爾值Flase

all():都為真,才為真

#all不接受多個字元串作為參數,隻能将這些參數放到一個清單(或元祖等)中
>>> print(all(,True,,['qwe','wer',],'qwe'))
Traceback (most recent call last):
  File "<stdin>", line , in <module>
TypeError: all() takes exactly one argument ( given)
#因為0被python認為是False,是以整體為False
>>> print(all(['qwe','wer',True,,]))
False
#改成1後就變成True了,
>>> print(all(['qwe','wer',True,,]))
True
           

any():任一為真,則為真

>>> print(any([None,,[],(),]))
False
>>> print(any([None,,[],(),,]))
True
           

數字進制轉換:bin(),oct(),int(),hex(),

#初始化變量
>>> ret=
#十進制轉為二進制
>>> print(bin(ret))

#十進制轉八進制
>>> print(oct(ret))

#十進制轉為十進制
>>> print(int(ret))

#十進制轉十六進制
>>> print(hex(ret))


           

bool():判斷布爾值

>>> print(bool())
False
>>> print(bool())
True
>>> print(bool(None))
False
>>> print(bool(""))
False
>>> print(bool("qwertw"))
True
           

float():将整型數字轉為浮點數型

round(float(),num):将浮點型數字,四舍五入到小數點後指定位數(num)

>>> reg=
>>> float(reg)

>>> ret = reg/
>>> round(ret,)

>>> print(ret)

           

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)

>>> 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 = 
>>> b = 
>>> divmod(a,b)
(, )
           

借此可以實作一個小案例:(共234條記錄,每頁顯示25條,共需要幾頁)

total = 
per = 
result = divmod(total,per)
if result[] == :
    ret = result[]
else:
    ret = result[]
print(ret)
           

enumerate(): 疊代器,以list的形勢傳回索引和值

#建立對象來表現
a = [ ,,,,,[,,,,]]
ret = enumerate(a)
print(ret)
print(list(ret))

    > <enumerate object at >
    > [(, ), (, ), (, ), (, ), (, ), (, [, , , ])]

#或者用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)
           

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 = [,,,,,,,,,,,,]
reg = filter(lambda a:a>,ret)

print(reg,type(reg))
print(list(reg))
           

注意輸出,如果直接列印傳回的對象reg,則會給出記憶體位址,再來看看類型,class‘filter’,是以要得到結果就得使用可疊代對象的類 再次建立對象’list(reg)’

filter object at > <class 'filter'>
[, , , ]
           

【重要】map(): 對可疊代對象進行操作

ret = ,]
pjt = map(lambda b:print(b),ret)

print(pjt,type(pjt))
print(list(pjt))
           

輸出,類似filter的結果,可自行體悟

<map object at > <class 'map'>












[None, None, None, None, None, None, None, None, None, None, None, None]
           

id():擷取表達式所在記憶體位址

ret = [,,,,,,,,,,,,]
reg = id(ret)
print(reg)
           
D:\python\python.exe D:/python/Project-/tmp/内建.py

           

isinstance() :判斷是否為某個類的對象,傳回True & Flase

age = 
print(isinstance(age,str))
print(isinstance(age,int))
           

len(): 傳回字元長度

ps:注意是字元長度,不是位元組長度,一個字母,一個漢字都被分為是一個字元

#int整數類,沒有len方法,是以無法調用,隻能以str類建立對象
age = '31'
name = '詹姆斯'
fav = 'MVP'
dig = ]
print(len(age),len(name),len(fav),len(dig))
           
D:\python\python.exe D:/python/Project-/tmp/内建.py
   
           

global() 傳回目前代碼環境的全局變量,locals() 傳回目前代碼環境的局部變量, 傳回的是字典類型

name = '詹姆斯'

def newinfo():
    fav = '總冠軍'
    age = 
    print('15-16賽季,聯盟最強')
    print(globals())
    print(locals())

newinfo()
           
-賽季,聯盟最強
{'newinfo': <function newinfo at >, '__loader__': <_frozen_importlib_external.SourceFileLoader object at >, '__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': }
           

max() min() sum() :取最大值、最小值、求和

ret = [,,,,,,,,,,,,]
print(max(ret),min(ret),sum(ret))
           
D:\python\python.exe D:/python/Project-/tmp/内建.py
  
           

pow(x,y,z): 兩個參數時表示x的y次方 ;三個參數時表示 x**y %z,在為取餘

reg = pow(,)
ret = pow(,,)
print(reg,ret)
           
D:\python\python.exe D:/python/Project-/tmp/内建.py
 
           

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-/tmp/内建.py
<zip object at > <class 'zip'>
[(, , ), (, , )]
           

最後介紹一下3.5和2.7的一下差別

# python3.5  可按照字元來周遊,也可按照位元組
for i in "詹姆斯":
    print(i)
a = "詹姆斯"
print(a[:], a[:], a[:])

# python2.7 #隻能按照位元組
a = "詹姆斯"
print a[:], a[:], a[:]
           
D:\python\python.exe D:/python/Project-/tmp/内建.py
詹
姆
斯
詹姆斯  

詹姆斯