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)
- 未完待续