1、內置函數(python3.x)html
內置參數詳解官方文檔: https://docs.python.org/3/library/functions.html?highlight=built#ascii python
1、數學運算類python3.x
abs(x) | 求絕對值 一、參數能夠是整型,也能夠是複數 二、若參數是負數,則返回負數的模 |
complex([real[, imag]]) | 建立一個複數 |
divmod(a, b) | 分別取商和餘數 注意:整型、浮點型均可以 |
float([x]) | 將一個字符串或數轉換爲浮點數。若是無參數將返回0.0 |
int([x[, base]]) | 將一個字符轉換爲int類型,base表示進制 |
long([x[, base]]) | 將一個字符轉換爲long類型 |
pow(x, y[, z]) | 返回x的y次冪 |
range([start], stop[, step]) | 產生一個序列,默認從0開始 |
round(x[, n]) | 四捨五入 |
sum(iterable[, start]) | 對集合求和 |
oct(x) | 將一個數字轉化爲8進制 |
hex(x) | 將整數x轉換爲16進制字符串 |
chr(i) | 返回整數i對應的ASCII字符 |
bin(x) | 將整數x轉換爲二進制字符串 |
bool([x]) | 將x轉換爲Boolean類型 |
2、集合類操做數據結構
basestring() | str和unicode的超類 不能直接調用,能夠用做isinstance判斷 |
format(value [, format_spec]) | 格式化輸出字符串 格式化的參數順序從0開始,如「I am {0},I like {1}」 |
unichr(i) | 返回給定int類型的unicode |
enumerate(sequence [, start = 0]) | 返回一個可枚舉的對象,該對象的next()方法將返回一個tuple |
iter(o[, sentinel]) | 生成一個對象的迭代器,第二個參數表示分隔符 |
max(iterable[, args...][key]) | 返回集合中的最大值 |
min(iterable[, args...][key]) | 返回集合中的最小值 |
dict([arg]) | 建立數據字典 |
list([iterable]) | 將一個集合類轉換爲另一個集合類 |
set() | set對象實例化 |
frozenset([iterable]) | 產生一個不可變的set |
str([object]) | 轉換爲string類型 |
sorted(iterable[, cmp[, key[, reverse]]]) | 隊集合排序 |
tuple([iterable]) | 生成一個tuple類型 |
xrange([start], stop[, step]) | xrange()函數與range()相似,但xrnage()並不建立列表,而是返回一個xrange對象,它的行爲與列表類似,可是隻在須要時才計算列表值,當列表很大時,這個特性能爲咱們節省內存 |
3、邏輯判斷app
all(iterable) | 一、集合中的元素都爲真的時候爲真 二、特別的,若爲空串返回爲True |
any(iterable) | 一、集合中的元素有一個爲真的時候爲真 二、特別的,若爲空串返回爲False |
cmp(x, y) | 若是x < y ,返回負數;x == y, 返回0;x > y,返回正數 |
4、反射ssh
5、IO操做函數
6、其餘post
help()--幫助信息性能
__import__()--沒太看明白了,看到了那句「Direct use of __import__() is rare」以後就沒心看下去了ui
apply()、buffer()、coerce()、intern()---這些是過時的內置函數,故不說明
7、後記
內置函數,通常都是由於使用頻率比較頻繁或是是元操做,因此經過內置函數的形式提供出來,經過對python的內置函數分類分析能夠看出來:基本的數據操做基本都是一些數學運算(固然除了加減乘除)、邏輯操做、集合操做、基本IO操做,而後就是對於語言自身的反射操做,還有就是字符串操做,也是比較經常使用的,尤爲須要注意的是反射操做。
8、內置函數使用示例
一、abs 絕對值
1 print(abs(-1)) 2 print(abs(1))
執行結果:
1 1 2 1
二、all 全部的都爲真,他才爲真
1 print(all([1,2,'1'])) 2 print(all([1,2,'1',''])) 3 print(all('')) #若是可迭代對象是空,就返回True
執行結果:
1 True 2 False 3 True
三、any 集合中的元素有一個爲真的時候爲真, 特別的,若爲空串返回爲False
1 print(any([0,''])) 2 print(any([0,'',1]))
執行結果:
1 False 2 True
四、bin 把十進制轉成二進制
1 print(bin(3))
執行結果:
1 0b11
五、bool 布爾值 空,None,0的布爾值爲False,其他都爲True
1 print(bool('')) #空字符串,返回值None 2 print(bool(None)) 3 print(bool(0))
執行結果:
1 False 2 False 3 False
六、bytes 把字符串轉成字節
ps1:
1 name='你好' 2 print(bytes(name,encoding='utf-8')) #手動把字符串編碼,轉成二進制 3 print(bytes(name,encoding='utf-8').decode('utf-8')) #須要把字符串進行編碼,再解碼(用什麼編碼,就用什麼解碼)
執行結果:
1 b'\xe4\xbd\xa0\xe5\xa5\xbd' 2 你好
ps2:
1 name='你好' 2 print(bytes(name,encoding='gbk')) 3 print(bytes(name,encoding='gbk').decode('gbk'))
執行結果:
1 b'\xc4\xe3\xba\xc3' 2 你好
ps3: ascll不能編碼中文,會報錯
1 name='你好' 2 print(bytes(name,encoding='ascii')) #ascii不能編碼中文,會報錯
執行結果:
1 Traceback (most recent call last): 2 File "D:/python/day7/built-in functions.py", line 33, in <module> 3 print(bytes(name,encoding='ascii')) #ascll不能編碼中文,會報錯 4 UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
七、ascll 碼對應的編碼
1 print(chr(46)) #ascll 碼對應的編碼
執行結果:
1 .
八、dir 顯示函數內置屬性和方法
1 print(dir(dict)) #打印內置屬性和方法
執行結果:
1 ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
九、divmod 取商得餘數,用於作分頁顯示功能
1 print(divmod(10,3)) #取商得餘數,用於作分頁顯示
執行結果:
1 (3, 1)
十、eval 把字符串中的數據結構給提取出來
1 dic={'name':'alex'} #字典類型轉成字符串 2 dic_str=str(dic) 3 print(dic_str) 4 5 d1=eval(dic_str) #eval:把字符串中的數據結構給提取出來 6 print(d1)
執行結果:
1 {'name': 'alex'} 2 3 {'name': 'alex'}
十一、可hash的數據類型即不可變數據類型,不可hash的數據類型便可變數據類型
1 #hash的做用:去網上下載軟件,判斷是否被人修改,經過比對hash值,就知道 2 print(hash('12sdfdsaf3123123sdfasdfasdfasdfasdfasdfasdfasdfasfasfdasdf')) 3 print(hash('12sdfdsaf31231asdfasdfsadfsadfasdfasdf23')) 4 5 name='alex' 6 print(hash(name)) 7 print(hash(name)) 8 9 print('--->before',hash(name)) 10 name='sb' 11 print('=-=>after',hash(name))
執行結果:
1 1982976672 2 864959982 3 -2006403263 4 -2006403263 5 --->before -2006403263 6 =-=>after 805524431
十二、help 查看函數用法的說細信息
1 print(help(all)) #查看函數用法的詳細信息
執行結果:
1 Help on built-in function all in module builtins: 2 3 all(iterable, /) 4 Return True if bool(x) is True for all values x in the iterable. 5 6 If the iterable is empty, return True. 7 8 None
1三、bin、hex、oct 進制轉換
1 print(bin(10)) #10進制->2進制 2 print(hex(12)) #10進制->16進制 3 print(oct(12)) #10進制->8進制
執行結果:
1 0b1010 #10進制->2進制
2 0xc #10進制->16進制
3 0o14 #10進制->8進制
1四、isinstance判斷類型
1 print(isinstance(1,int)) #判斷是否是int類型 2 print(isinstance('abc',str)) #判斷字符串 3 print(isinstance([],list)) #判斷列表 4 print(isinstance({},dict)) #判斷字典 5 print(isinstance({1,2},set)) #判斷集合
執行結果:
1 True 2 True 3 True 4 True 5 True
1五、globals 全局變量
ps1:
1 name='哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈粥少陳' 2 print(globals()) #全局變量
執行結果:
1 {'__doc__': None, '__name__': '__main__', '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x01625C30>, '__cached__': None, 'name': '哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈粥少陳', '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__spec__': None, '__file__': 'D:/python/day7/built-in functions.py'}
ps2: __file__ 直接打印文件名
1 name='哈哈哈哈哈哈哈哈哈哈哈哈哈哈啊哈粥少陳' 2 print(__file__) #直接打印文件名
執行結果:
1 D:/python/day7/built-in functions.py
ps3: globals 打印全局變量,locals 打印上一層的變量
1 def test(): 2 age='1111111111111111111111111111111111111111111111111111111111111' 3 print(globals()) #打印全局變量 4 print(locals()) #打印上一層的變量 5 6 test()
執行結果:
1 {'__builtins__': <module 'builtins' (built-in)>, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x01CD5C30>, '__file__': 'D:/python/day7/built-in functions.py', 'test': <function test at 0x01DE2F60>, '__package__': None, '__cached__': None, '__name__': '__main__', '__spec__': None, '__doc__': None} 2 {'age': '1111111111111111111111111111111111111111111111111111111111111'}
1六、max 最大值 和 min最小值
ps1:
1 l=[1,3,100,-1,2] 2 print(max(l)) 3 print(min(l))
執行結果:
1 100 #最大值 2 -1 #最小值
ps2: max 高級用法
說明:
一、max函數處理的是可迭代對象,至關於一個for循環取出每一個元素進行比較
注意:不一樣類型之間不能進行比較
二、每一個元素間進行比較,是從每一個元素的第一位置依次比較,若是這一個位置分出大小,後
面的都不須要比較了,直接得出這倆元素的大小。
1 age_dic={'alex_age':18,'wupei_age':20,'zsc_age':100,'lhf_age':30} 2 print(max(age_dic.values())) #取出最大年齡 3 print(max(age_dic)) #默認比較的是字典的key
執行結果:
1 100 2 zsc_age
ps3: 取出年齡最大的key和values
1 age_dic={'alex_age':18,'wupei_age':20,'zsc_age':100,'lhf_age':30} 2 for item in zip(age_dic.values(),age_dic.keys()): #[(18,'alex_age') (20,'wupeiqi_age') () () ()] 3 print(item) 4 5 #取出年齡最大的key和values 6 print('=======>',list(max(zip(age_dic.values(),age_dic.keys())))) #max和zip聯合使用
執行結果:
1 (100, 'zsc_age') 2 (30, 'lhf_age') 3 (18, 'alex_age') 4 (20, 'wupei_age') 5 6 7 =======> [100, 'zsc_age'] #取出年齡最大的key和values
ps4:
1 l=[ 2 (5,'e'), 3 (1,'b'), 4 (3,'a'), 5 (4,'d'), 6 ] 7 l1=['a10','b12','c10',100] #不一樣類型之間不能進行比較 8 l1=['a10','a2','a10'] #不一樣類型之間不能進行比較 9 print(list(max(l))) 10 11 print('--->',list(max(l1)))
執行結果:
1 [5, 'e'] 2 ---> ['a', '2']
1七、zip 將對象逐一配對
ps1:
1 print(list(zip(('a','n','c'),(1,2,3)))) 2 print(list(zip(('a','n','c'),(1,2,3,4)))) 3 print(list(zip(('a','n','c','d'),(1,2,3))))
執行結果:
1 [('a', 1), ('n', 2), ('c', 3)] 2 [('a', 1), ('n', 2), ('c', 3)] 3 [('a', 1), ('n', 2), ('c', 3)]
ps2:
1 p={'name':'alex','age':18,'gender':'none'} 2 print(list(zip(p.keys(),p.values()))) 3 print(list(p.keys())) #取keys 4 print(list(p.values())) #values 5 6 print(list(zip(['a','b'],'12345'))) #列表,只要是序列就能夠打印出來
執行結果:
1 [('age', 18), ('name', 'alex'), ('gender', 'none')] 2 ['age', 'name', 'gender'] 3 [18, 'alex', 'none'] 4 [('a', '1'), ('b', '2')]
ps3:
max總結:
1 l=[1,3,100,-1,2] 2 print(max(l)) #比較出最大值 3 4 5 dic={'age1':18,'age2':10} 6 print(max(dic)) #比較的是key 7 8 9 print(max(dic.values())) #比較的是key,可是不知道是那個key對應的值 10 11 12 print(max(zip(dic.values(),dic.keys()))) #結合zip使用
執行結果:
1 100 #比較大小,得出最大值 2 3 age2 #比較的是key 4 5 18 #比較的是key,可是不知道是那個key對應的值 6 7 (18, 'age1') #結合zip拿用
ps4:
1 people=[ 2 {'name':'alex','age':1000}, 3 {'name':'wupei','age':10000}, 4 {'name':'yuanhao','age':9000}, 5 {'name':'linhaifeng','age':18}, 6 ] 7 # max(people,key=lambda dic:dic['age']) 8 print('周紹陳取出來沒有',max(people,key=lambda dic:dic['age'])) #提取年齡中的values,再進行比較 9 10 #上面題分解步驟,先取出ret的值,再給max進行比較 11 people=[ 12 {'name':'alex','age':1000}, 13 {'name':'wupei','age':10000}, 14 {'name':'yuanhao','age':9000}, 15 {'name':'linhaifeng','age':18}, 16 ] 17 18 ret=[] 19 for item in people: 20 ret.append(item['age']) 21 print(ret) 22 max(ret)
執行結果:
1 #提取年齡中的values,再進行比較大小,得出age最大的 2 3 周紹陳取出來沒有 {'name': 'wupei', 'age': 10000} 4 5 6 #上面題分解步驟,先取出ret的值,再給max進行比較,得出的值: 7 8 [1000, 10000, 9000, 18]
ps5:
chr : 返回一個字符串,其ASCII碼是一個整型.好比chr(97)返回字符串'a'。參數i的範圍在0- 255之間。
ord: 參數是一個ascii字符,返回值是對應的十進制整數
pow: 幾的幾回方
1 print(chr(97)) #ascll碼應對的編碼 2 3 print(ord('a')) #ascll碼應對的數字 4 5 print(pow(3,3)) #3**3 幾的幾回方,至關於3的3次方 6 7 print(pow(3,3,2)) #3**3%2 3的3次方,取餘
執行結果:
1 a #ascll碼應對的編碼 2 3 97 #ascll碼應對的數字 4 5 27 #3**3 幾的幾回方,至關於3的3次方 6 7 1 #3**3%2 3的3次方,取餘
1八、reversed 反轉
1 l=[1,2,3,4] 2 print(list(reversed(l))) 3 print(l)
執行結果:
1 [4, 3, 2, 1] #反轉 2 [1, 2, 3, 4]
1九、round 四捨五入
1 print(round(3.5)) #四捨五入
執行結果:
1 4
20、set 集合
1 print(set('hello')) #集合
執行結果:
1 {'l', 'e', 'o', 'h'}
2一、slice 切片
1 l='hello' 2 s1=slice(3,5) #切片 取3到5的元素 3 s2=slice(1,4,2) #切片,指定步長爲2 4 print(l[3:5]) 5 6 print(l[s1]) #切片 7 print(l[s2]) 8 9 print(s2.start) #開始 10 print(s2.stop) #結束 11 print(s2.step) 步長
執行結果:
1 lo 2 3 lo 4 5 el 6 7 1 8 9 4 10 11 2
2二、sorted 排序
ps1:
1 l=[3,2,1,5,7] 2 l1=[3,2,'a',1,5,7] 3 print(sorted(l)) #排序 4 # print(sorted(l1)) #直接運行會報錯,由於排序本質就是在比較大小,不一樣類型之間不能夠比較大小
執行結果:
1 [1, 2, 3, 5, 7]
ps2:
1 people=[ 2 {'name':'alex','age':1000}, 3 {'name':'wupei','age':10000}, 4 {'name':'yuanhao','age':9000}, 5 {'name':'linhaifeng','age':18}, 6 ] 7 print(sorted(people,key=lambda dic:dic['age'])) #按年齡進行排序
執行結果:
1 [{'age': 18, 'name': 'linhaifeng'}, {'age': 1000, 'name': 'alex'}, {'age': 9000, 'name': 'yuanhao'}, {'age': 10000, 'name': 'wupei'}]
ps3:
1 name_dic={ 2 'abyuanhao': 11900, 3 'alex':1200, 4 'wupei':300, 5 } 6 print(sorted(name_dic)) #按key排序 7 8 print(sorted(name_dic,key=lambda key:name_dic[key])) #取出字典的values 9 10 print(sorted(zip(name_dic.values(),name_dic.keys()))) #按價格從低到高排序
執行結果:
1 ['abyuanhao', 'alex', 'wupei'] 2 3 ['wupei', 'alex', 'abyuanhao'] 4 5 [(300, 'wupei'), (1200, 'alex'), (11900, 'abyuanhao')]
2三、str , type
str 轉換成字符型
type 查看某一個東西的數據類型
ps1:
1 print(str('1')) #str 轉換成字符型 2 print(type(str({'a':1}))) #type 查看數據類型 3 4 dic_str=str({'a':1}) 5 print(type(eval(dic_str))) #eval 轉換數據類型
執行結果:
1 1 2 <class 'str'> 3 <class 'dict'>
ps2:
int類型加1
1 msg='123' 2 if type(msg) is str: 3 msg=int(msg) 4 res=msg+1 5 print(res)
執行結果:
1 124
2四、vars 跟一個列表或多個字典
1 def test(): 2 msg='撒旦法阿薩德防撒旦浪費艾絲凡阿斯蒂芬' 3 print(locals()) #打印出上一層的值,若是上一層沒有,再往上找 4 print(vars()) #若是沒有參數,跟locals同樣,若是有參數,查看某一個方法,顯示成字典的方式 5 test() 6 print(vars(int))
執行結果:
1 {'msg': '撒旦法阿薩德防撒旦浪費艾絲凡阿斯蒂芬'} 2 {'msg': '撒旦法阿薩德防撒旦浪費艾絲凡阿斯蒂芬'} 3 {'denominator': <attribute 'denominator' of 'int' objects>, '__mod__': <slot wrapper '__mod__' of 'int' objects>, '__radd__': <slot wrapper '__radd__' of 'int' objects>, '__floordiv__': <slot wrapper '__floordiv__' of 'int' objects>, '__doc__': "int(x=0) -> integer\nint(x, base=10) -> integer\n\nConvert a number or string to an integer, or return 0 if no arguments\nare given. If x is a number, return x.__int__(). For floating point\nnumbers, this truncates towards zero.\n\nIf x is not a number or if base is given, then x must be a string,\nbytes, or bytearray instance representing an integer literal in the\ngiven base. The literal can be preceded by '+' or '-' and be surrounded\nby whitespace. The base defaults to 10. Valid bases are 0 and 2-36.\nBase 0 means to interpret the base from the string as an integer literal.\n>>> int('0b100', base=0)\n4", '__ceil__': <method '__ceil__' of 'int' objects>, '__sizeof__': <method '__sizeof__' of 'int' objects>, '__pos__': <slot wrapper '__pos__' of 'int' objects>, '__gt__': <slot wrapper '__gt__' of 'int' objects>, '__rtruediv__': <slot wrapper '__rtruediv__' of 'int' objects>, '__sub__': <slot wrapper '__sub__' of 'int' objects>, '__rdivmod__': <slot wrapper '__rdivmod__' of 'int' objects>, '__new__': <built-in method __new__ of type object at 0x5D677028>, '__rshift__': <slot wrapper '__rshift__' of 'int' objects>, '__rmod__': <slot wrapper '__rmod__' of 'int' objects>, '__neg__': <slot wrapper '__neg__' of 'int' objects>, '__xor__': <slot wrapper '__xor__' of 'int' objects>, '__rmul__': <slot wrapper '__rmul__' of 'int' objects>, '__repr__': <slot wrapper '__repr__' of 'int' objects>, '__hash__': <slot wrapper '__hash__' of 'int' objects>, 'to_bytes': <method 'to_bytes' of 'int' objects>, 'from_bytes': <method 'from_bytes' of 'int' objects>, 'real': <attribute 'real' of 'int' objects>, '__lt__': <slot wrapper '__lt__' of 'int' objects>, '__invert__': <slot wrapper '__invert__' of 'int' objects>, '__eq__': <slot wrapper '__eq__' of 'int' objects>, '__float__': <slot wrapper '__float__' of 'int' objects>, '__round__': <method '__round__' of 'int' objects>, '__ror__': <slot wrapper '__ror__' of 'int' objects>, '__le__': <slot wrapper '__le__' of 'int' objects>, '__rlshift__': <slot wrapper '__rlshift__' of 'int' objects>, 'bit_length': <method 'bit_length' of 'int' objects>, '__getnewargs__': <method '__getnewargs__' of 'int' objects>, '__index__': <slot wrapper '__index__' of 'int' objects>, '__rsub__': <slot wrapper '__rsub__' of 'int' objects>, '__format__': <method '__format__' of 'int' objects>, '__bool__': <slot wrapper '__bool__' of 'int' objects>, '__or__': <slot wrapper '__or__' of 'int' objects>, '__int__': <slot wrapper '__int__' of 'int' objects>, 'imag': <attribute 'imag' of 'int' objects>, 'conjugate': <method 'conjugate' of 'int' objects>, '__ge__': <slot wrapper '__ge__' of 'int' objects>, '__and__': <slot wrapper '__and__' of 'int' objects>, '__abs__': <slot wrapper '__abs__' of 'int' objects>, '__floor__': <method '__floor__' of 'int' objects>, '__divmod__': <slot wrapper '__divmod__' of 'int' objects>, '__trunc__': <method '__trunc__' of 'int' objects>, '__rrshift__': <slot wrapper '__rrshift__' of 'int' objects>, '__mul__': <slot wrapper '__mul__' of 'int' objects>, '__pow__': <slot wrapper '__pow__' of 'int' objects>, '__str__': <slot wrapper '__str__' of 'int' objects>, '__ne__': <slot wrapper '__ne__' of 'int' objects>, '__getattribute__': <slot wrapper '__getattribute__' of 'int' objects>, '__truediv__': <slot wrapper '__truediv__' of 'int' objects>, '__add__': <slot wrapper '__add__' of 'int' objects>, '__rand__': <slot wrapper '__rand__' of 'int' objects>, '__rfloordiv__': <slot wrapper '__rfloordiv__' of 'int' objects>, '__lshift__': <slot wrapper '__lshift__' of 'int' objects>, '__rxor__': <slot wrapper '__rxor__' of 'int' objects>, 'numerator': <attribute 'numerator' of 'int' objects>, '__rpow__': <slot wrapper '__rpow__' of 'int' objects>}
2五、import 模塊
一、先建立一個test.py文件
寫入內容以下:
1 def say_hi(): 2 print('你好啊林師傅')
二、再調用這個模塊
1 import test #導入一個模塊,模塊就是一個py文件 2 test.say_hi()
執行結果:
1 你好啊林師傅
2六、__import__ :導入一個字符串類型模塊,就要用__import__
一、先建立一個test.py文件
寫入內容以下:
1 def say_hi(): 2 print('你好啊林師傅')
二、再調用這個模塊
1 module_name='test' 2 m=__import__(module_name) #有字符串的模塊 3 m.say_hi()
執行結果:
1 你好啊林師傅