python常用內置函數的作用


abs()    #獲取絕對值

chr()    #返回數字對應的ASCII字符

cmp(x,y)    #如果x<y 返回-1,x==y返回0 ,x> y返回1

compile()     #函數將一個字符串編譯為字節代碼。
str = 'for i in  [1,2,3,4,5,6,7] :print(i)'   #name
c = compile(str,'','exec')
exec(str)

exec()    #函數將一句string類型的python代碼執行
str = 'for i in  [1,2,3,4,5,6,7] :print(i)'   #name
c = compile(str,'','exec')
exec(str)

eval()    #函數將一個算數表達式執行

dict()    #函數用來創建字典類型

zip()    #函數可以將多個可迭代的對象按照相同的index轉化為最短的tuple
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 打包為元組的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c)              # 元素個數與最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped)          # 與 zip 相反,可理解為解壓,返回二維矩陣式
[(1, 2, 3), (4, 5, 6)]

dir()    #獲取當前類型的方法
print(dir(list))
['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

divmod()    #函數把除數和余數運算結果結合起來,返回一個包含商和余數的元組(a // b, a % b)。
print(divmod(7,2))   
(3, 1)

enumerate()    #把可遍歷的對象組合成一個枚舉對象,(索引,字段本身)
>>>seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1))       # 小標從 1 開始
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]

execfile()    #函數可以用來執行一個文件。

format()    #用{}和:代替以前的%

from functools import reduce
a = 1
b = 2
print(a+1 if a>b else b+1) #列表推導式 3
lis = [1,2,3,4,5]
print([i for i in lis if i%2 ==0]) #列表推導式 [2, 4]
a = list(map(lambda x :x**2 if x%3 == 0 else x,lis)) # map
print(a) #[1, 2, 9, 4, 5]
b = reduce(lambda x,y:x+y,lis) #reduce 15
print(b)
print(list(filter(lambda x:x%3 ==0,lis))) #filter [3]
print(sorted(lis,reverse=True)) #sorted [5, 4, 3, 2, 1]
 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM