一、內置函數列表
二、常見內置函數用法
由於python內置函數較多,在此總結一下部分常見的內置函數的用法:
- abs(x)
功能:取數的絕對值
1 >>> abs(0) 2 0 3 >>> abs(-5) 4 5 5 >>>
- all(interable)
功能:判斷可迭代對象中的每個元素,如果均為真(非0)則返回true,反之返回false
1 >>> all([1,2,3]) 2 True 3 >>> all([0,1,2,3]) 4 False 5 >>>
- any(interable)
功能:也是判斷可迭代對象中的每個元素,不同的是只要有一個元素為真就返回true,反之返回false
1 >>> any(['a','b','c']) 2 True 3 >>> any([]) #空列表為假 4 False 5 >>> any([0]) 6 False 7 >>> any([0,1]) 8 True 9 >>>
- bin(x)
功能:把整數轉換成二進制
1 >>> bin(100) 2 '0b1100100' 3 >>> bin(1) 4 '0b1' 5 >>>
- bool(object)
功能:判斷對象,返回布爾值,為空或0則返回false,反之返回true
1 >>> bool('x') 2 True 3 >>> bool('') 4 False 5 >>> bool(0) 6 False 7 >>>
- bytearray[source[, encoding[, errors]]]
功能:把二進制字節轉換成可以修改的數組(列表)
1 >>> list1=bytearray('001',encoding='utf-8') 2 >>> list1 3 bytearray(b'001') 4 >>> list1[0] #以列表方式訪問元素,返回的是對應的ASCII碼 5 48 6 >>> list1[0]=99 #更新時也必須以ASCII碼的形式來更新 7 >>> list1 8 bytearray(b'c01') #更新后原列表變了 9 >>>
- bytes([source[, encoding[, errors]]])
功能:把字符串轉換成字節,但不能修改內容
1 >>> b = bytes("abcd",encoding="utf-8") 2 >>> b 3 b'abcd' 4 >>> b[1] 5 98 6 >>> b[1]=99 7 Traceback (most recent call last): 8 File "<stdin>", line 1, in <module> 9 TypeError: 'bytes' object does not support item assignment
- callable(object)
功能:判斷一個對象是否可以被調用,目前所知道的只有函數或類才可以通過調用符號()去調用。
1 >>> def func1(): 2 ... pass 3 ... 4 >>> callable(func1) 5 True 6 >>> a='test' 7 >>> callable(a) 8 False
- chr(x)
功能:把ASCII中的數字轉換成對應的字符
1 >>> chr(98) 2 'b'
- ord(x)
功能:獲取一個字符對應的ASCII碼
1 >>> ord('c') 2 99
- dict(**kwarg)、dict(mapping, **kwarg)、dict(iterable, **kwarg)
功能:生成一個字典
1 >>> dict 2 <class 'dict'> 3 >>> dict({('address','Chengdu'),('Num','028')}) #傳入一個set 4 {'address': 'Chengdu', 'Num': '028'} 5 >>> dict([('address','Chengdu'),('Num','028')]) #傳入list 6 {'address': 'Chengdu', 'Num': '028'} 7 >>> dict([['address','Chengdu'],['Num','028']]) 8 {'address': 'Chengdu', 'Num': '028'} 9 >>> dict((('address','Chengdu'),('Num','028'))) #傳入元組 10 {'address': 'Chengdu', 'Num': '028'} 11 >>>
- dir(object)
功能:查看一個對象的方法
1 >>> a=dict((('address','Chengdu'),('Num','028'))) 2 >>> dir(a) 3 ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__' 4 , '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', 5 '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', ' 6 __lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__seta 7 ttr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'co 8 py', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update 9 ', 'values']
- divmod(a,b)
功能:地板除,獲得一個元組,元組第一個元素是商,第二個元素是余數。
1 >>> divmod(9,2) 2 (4, 1)
- enumerate(iterable,start=0)
功能:遍歷一個iterable中,逐個返回索引和相應的元素(一個enumerate對象),start參數可設置索引起始值,默認從0開始
1 >>> test='abcd' 2 >>> for index,item in enumerate(test): 3 ... print(index,item) 4 ... 5 0 a 6 1 b 7 2 c 8 3 d 9 >>> print(list(enumerate(test))) 10 [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')] 11 >>> print(list(enumerate(test,start=2))) #start參數人為設定起始索引值,默認從0開始 12 [(2, 'a'), (3, 'b'), (4, 'c'), (5, 'd')] 13 >>> print(dict(enumerate(test))) 14 {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
- eval(expression, globals=None, locals=None)
功能:進行簡單的數學運算,對於符合其他特征不可計算的字符串,進行類型轉換,比如可以把符合特征的字符串轉換成int類型,list,tuple,dict等。
1 >>> eval('100') 2 100 3 >>> type(eval('100')) 4 <class 'int'> 5 >>> eval("[1,2,3]") 6 [1, 2, 3] 7 >>> eval("(1,2,3)") 8 (1, 2, 3) 9 >>> eval("{1:'name',2:'male',3:'age'}") 10 {1: 'name', 2: 'male', 3: 'age'}
- filter(function, iterable)
功能:根據function定義的過濾條件,篩選出Iterable中符合條件的數據。
1 >>> a=filter(lambda x:x %2 == 0, [0,1,2,3,4]) 2 >>> print(a) 3 <filter object at 0x0000000001E9BE48> #經filter處理后返回的是一個filter對象 4 >>> for i in a: 5 ... print(i) 6 ... 7 0 8 2 9 4
- map(function, iterable)
功能:接收參數function和可迭代對象iterable,對於每個迭代的元素一一進行函數運算,然后返回相應的結果(簡單理解為一對一映射處理)1 >>> def func1(x): 2 ... return x * 2 3 ... 4 >>> rs=map(func1,range(5)) 5 >>> for i in rs: 6 ... print(i) 7 ... 8 0 9 2 10 4 11 6 12 8 13 >>> rs 14 <map object at 0x00000000021DBE10>
- reduce(function,iterable,initializer)
功能:將一個帶有兩個參數的方法累計應用到一個可迭代的對象的元素上(function必須接收兩個參數,遍歷可迭代對象的元素,把上一次計算的結果作為下一次計算的第一個參數),以便把可迭代對象規約為一個單一的值,即大數據中的reduce規約計算。其中第三個參數初始值是可選的,如果給出了初始值,則把初始值作為第一個計算的第一個參數。
1 >>> def f(x,y): 2 ... return x+y 3 ... 4 >>> reduce(f,[1,3,5,7,9]) 5 Traceback (most recent call last): 6 File "<stdin>", line 1, in <module> 7 NameError: name 'reduce' is not defined 8 >>> from functools import reduce #注意這里需要先導入后才能使用 9 >>> reduce(f,[1,3,5,7,9]) 10 25 11 >>> reduce(f,[1,3,5,7,9],100) #給出初始值100 12 125
- float
功能:把一個數字形式的字符串轉換為浮點類型的數據。1 >>> float('a') 2 Traceback (most recent call last): 3 File "<stdin>", line 1, in <module> 4 ValueError: could not convert string to float: 'a' #a不是數字形式,無法轉換 5 >>> 6 >>> float('1') 7 1.0 8 >>> float('1.23') 9 1.23
- fronzenset(interable)
功能:把一個可迭代對象轉換為一個不可變的集合(雙重特性,首先是符合集合的特性,其次是不可變)1 >>> res=frozenset([1,1,2,2,3]) 2 >>> res 3 frozenset({1, 2, 3}) #集合中的元素不可重復,符合集合特征 4 >>> res.add(4) #不能針對該集合增加元素,不可變 5 Traceback (most recent call last): 6 File "<stdin>", line 1, in <module> 7 AttributeError: 'frozenset' object has no attribute 'add' 8 >>> dir(res) #沒有可變方法 9 ['__and__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '_ 10 _eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__ini 11 t__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', 12 '__new__', '__or__', '__rand__', '__reduce__', '__reduce_ex__', '__repr__', '__r 13 or__', '__rsub__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__' 14 , '__subclasshook__', '__xor__', 'copy', 'difference', 'intersection', 'isdisjoi 15 nt', 'issubset', 'issuperset', 'symmetric_difference', 'union'] 16 >>>
- globals()
功能:返回程序中所有的變量鍵值對(key 變量名, value 變量值,全局變量)1 >>> def foo(x): 2 ... global a 3 ... a=10 4 ... b=20 5 ... print(globals()) 6 ... 7 >>> foo() 8 Traceback (most recent call last): 9 File "<stdin>", line 1, in <module> 10 TypeError: foo() missing 1 required positional argument: 'x' 11 >>> foo(1) 12 {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <cl 13 ass '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': { 14 }, '__builtins__': <module 'builtins' (built-in)>, 'f': <function f at 0x0000000 15 001D23E18>, 'reduce': <built-in function reduce>, 'res': frozenset({1, 2, 3}), ' 16 test': <function test at 0x00000000023DAEA0>, 'foo': <function foo at 0x00000000 17 02543840>, 'a': 10} #定義的全局變量已經獲取打印到 18 19 >>> def foo2(): 20 ... global a 21 ... a=100 22 ... print(globals().get('a')) #直接獲取全局變量的值 23 ... 24 >>> foo2() 25 100
- locals()
功能:與globals()類似,但返回的是局部變量1 >>> def foo(x): 2 ... a='hehe' 3 ... print(locals()) 4 ... 5 >>> foo(1) 6 {'a': 'hehe', 'x': 1} 7 >>>
- hash()
功能:根據一定的算法生成固定的映射結果,相同的輸入生成相同的輸出1 >>> hash('xy') 2 6325275833896794579 3 >>> hash('xy') 4 6325275833896794579 5 >>> hash('100') 6 -93280025000303673 7 >>> hash(100) 8 100 9 >>>
- max(iterable)
功能:返回一個可迭代對象的最大值1 >>> max((1,2,3)) 2 3 3 >>> max({1,2,6}) 4 6
- min(interable)
功能:返回一個可迭代對象的最小值1 >>> max((1,2,3)) 2 3 3 >>> max({1,2,6}) 4 6
- input()
功能:輸入字符串1 >>> input(':') 2 :hehe 3 'hehe'
- list()
功能:把其他的序列轉換成列表1 >>> list({1,2,3}) 2 [1, 2, 3]
- set()
功能:把其他的序列(可迭代對象)轉換成集合1 >>> set({1:'a',2:'b'}) 2 {1, 2} 3 >>> set(range(5)) 4 {0, 1, 2, 3, 4}
- hex()
功能:轉換十六進制1 >>> hex(16) 2 '0x10' 3 >>>
- oct()
功能:轉換八進制1 >>> oct(8) 2 '0o10' 3 >>> oct(7) 4 '0o7'
- sorted(iterable[, key][, reverse])
功能:對一個序列進行排序1 >>> a={1:'a',2:'c',3:'b'} 2 >>> sorted(a) #默認只是排序key 3 [1, 2, 3] 4 >>> sorted(a.items()) #a.items返回的是包含鍵值對元組的列表,這里還是按key排序 5 [(1, 'a'), (2, 'c'), (3, 'b')] 6 >>> sorted(a.items(),key=lambda x:x[1]) #指定鍵值對中的value作為排序的key,因此按value來排序 7 [(1, 'a'), (3, 'b'), (2, 'c')] 8 >>> print(a.items()) 9 dict_items([(1, 'a'), (2, 'c'), (3, 'b')])
- zip(*iterables)
功能:組合兩個對象(zip中文拉鏈的意思),一一對應起來(如果有一個序列的個數更少,則按少的那個來)。1 >>> a=[1,2,3] 2 >>> b={'a','b'} 3 >>> for i in zip(a,b): 4 ... print(i) 5 ... 6 (1, 'a') 7 (2, 'b') 8 >>>
- __import__(name, globals=None, locals=None, fromlist=(), level=0)
功能:當導入的模塊是一個字符串時,用__import__()1 >>> import os 2 >>> __import__('os') 3 <module 'os' from 'C:\\Program Files (x86)\\python3.6.1\\lib\\os.py'>
先計算頭兩個元素:f(1, 3),結果為4;
再把結果和第3個元素計算:f(4, 5),結果為9;
再把結果和第4個元素計算:f(9, 7),結果為16;
再把結果和第5個元素計算:f(16, 9),結果為25;
由於沒有更多的元素了,計算結束,返回結果25。
典型的應用場景是:凡是要對一個可迭代獨享進行操作的,並且要有一個統計結果的,能夠用循環或者遞歸方式解決的問題,一般情況下都可以用reduce方式實現(比如統計一個集合中key重復的次數)。