Python給我們內置了很多實用的函數,我們不用導入庫就可以拿來使用;我們今天給他們分下類,分類進行講解:
一、數字操作
- 數據類型轉換
a = 1 print(bool(a)) # bool() 強制轉換成布爾類型 print(int(a)) # int() 強制轉換成整型 print(float(a)) # float() 強制轉換成浮點型 print(str(a)) # str() 強制轉換成字符串 print(complex(a)) # complex() 強制轉換成複數 # 輸出結果: # True # 1 # 1.0 # 1 # (1+0j)
- 進制轉換
a = 12 print(bin(a)) # bin() 將數字轉換成二進制 print(oct(a)) # oct() 將數字轉換成八進制 print(hex(a)) # hex() 將數字轉換成十六進制 # 輸出結果: # 0b1100 # 0o14 # 0xc
- 數學運算
1) 返回最大值a = [1,6,4,3,7,5] print(max(a)) # max(集合序列) # 輸出結果: # 7
a = [1,6,4,3,7,5] print(min(a)) # min(集合序列) # 輸出結果: # 1
a = -12 print(abs(a)) # abs(數值) # 輸出結果: # 12
print(divmod(10,3)) # divmod(被除數,除數) # 輸出結果: # (3, 1)
print(round(1.4)) print(round(1.5)) print(round(1.6)) # round(數值) # 輸出結果: # 1 # 2 # 2
print(pow(10,2)) print(pow(10,2,3)) # pow(a,b,c) → a^b → a的b次冪 # c 即爲求冪後取餘數 # 輸出結果: # 100 # 1
a = [1,2,3,4,5] print(sum(a)) # sum(集合序列) # 輸出結果: # 15
二、集合序列操作
- 集合序列轉換
a = [1,2,3,4,5] b = (1,2,3,4,5) print(tuple(a)) print(list(b)) # 輸出結果: # (1, 2, 3, 4, 5) # [1, 2, 3, 4, 5]
- 序列操作
1) 翻轉列表
a = [1,2,3,4,5] print(list(reversed(a))) # 輸出結果: # [5, 4, 3, 2, 1]
2) 列表切片
a = [1,2,3,4,5] print(a[1:4]) # 切片取區間數據 print(a[1:4:2]) # 切片取區間指定步長的數據 # a[頭位置,尾位置,步長] b = slice(1,4,2) # 創建切片規則 print(a[b]) # 按照規則進行切片 # 輸出結果: # [2, 3, 4] # [2, 4] # [2, 4]
3) 格式化數據
# 字符串對齊方式 print(format('hello','^20'),'end') print(format('hello','<20'),'end') print(format('hello','>20'),'end') # format(字符串,'對齊規則') # 輸出結果: # hello end # hello end # hello end
# 進制轉換 print(format(15,'b')) # 二進制 print(format(15,'d')) # 十進制 print(format(15,'o')) # 八進制 print(format(15,'x')) # 十六進制 print(format(15,'X')) # 十六進制(大寫) # 輸出結果: # 1111 # 15 # 17 # f # F
# 科學計數法 print(format(123456789,'e')) # 科學計數法,默認保留六位小數 print(format(123456789,'0.5e')) # 指定小數位數 print(format(12345678,'0.5E')) # 輸出結果: # 1.234568e+08 # 1.23457e+08 # 1.23457E+07
print(format(1.23456789,'f')) print(format(1.23456789,'0.5f')) # 輸出結果: # 1.234568 # 1.23457
3)
- 未完待續