python 內置函數大講堂
1. 內置函數
python的內置函數截止到python版本3.6.2,現在python一共為我們提供了68個內置函數。它們就是python提供給你直接可以拿來使用的所有函數。那今天我們就一起來認識一下python的內置函數。
上面就是內置函數的表,68個函數都在這兒了。這個表的順序是按照首字母的排列順序來的,你會發現都混亂的堆在一起。比如,oct和bin和hex都是做進制換算的,但是卻被寫在了三個地方。。。這樣非常不利於大家歸納和學習。那我把這些函數分成了6大類。你看下面這張圖:
上圖中,標紅的四大塊有56個方法。今天先學習這些。
1-1. 作用域相關的函數

基於字典的形式獲取局部變量和全局變量
globals()——獲取全局變量的字典
locals()——獲取執行本方法所在命名空間內的局部變量的字典
Output:
{'name': 'main', 'doc': None, 'package': None, 'loader': <_frozen_importlib_external.SourceFileLoader object at 0x00F6EE30>, 'spec': None, 'annotations': {}, 'builtins': <module 'builtins' (built-in)>, 'file': 'D:/Study/BaiduNetdiskDownload/day15課堂筆記/Func.py', 'cached': None}
{'name': 'main', 'doc': None, 'package': None, 'loader': <_frozen_importlib_external.SourceFileLoader object at 0x00F6EE30>, 'spec': None, 'annotations': {}, 'builtins': <module 'builtins' (built-in)>, 'file': 'D:/Study/BaiduNetdiskDownload/day15課堂筆記/Func.py', 'cached': None}
1-2. 其他

1-2-1. eval、exec、compile
eval() 將字符串類型的代碼執行並返回結果
print(eval('1+2+3+4'))
Output :
10
exec()將自字符串類型的代碼執行,返回位None.
此函數支持Python代碼的動態執行。object必須是字符串或代碼對象。如果它是一個字符串,則將該字符串解析為一組Python語句,然后執行該語句(除非發生語法錯誤),如果是代碼對象,則只執行它。在所有情況下,執行的代碼應該作為文件輸入有效(請參見“參考手冊”中的“文件輸入”部分)。請注意,
即使在傳遞給函數的代碼的上下文中,也不能在函數定義之外使用return和yield語句 exec()。返回值是None。
print(exec("1+2+3+4"))
exec("print('hello,world')")
Output:
None
hello,world
再看一段代碼
code = ''' import os print(os.path.abspath('.')) '''
code = ''' print(123) a = 20 print(a) '''
a = 10
exec(code,{'print':print},)
print(a)
#Ouput:
123
20
10
注意:如果把exec(code,{'print':print},)改成exec(code),則輸出:123 20 20
compile 將字符串類型的代碼編譯。代碼對象能夠通過exec語句來執行或者eval()進行求值。
參數說明:
參數source:字符串或者AST(Abstract Syntax Trees)對象。即需要動態執行的代碼段。
參數 filename:代碼文件名稱,如果不是從文件讀取代碼則傳遞一些可辨認的值。當傳入了source參數時,filename參數傳入空字符即可。
參數model:指定編譯代碼的種類,可以指定為 ‘exec’,’eval’,’single’。當source中包含流程語句時,model應指定為‘exec’;當source中只包含一個簡單的求值表達式,model應指定為‘eval’;當source中包含了交互式命令語句,model應指定為'single'。
>>> #流程語句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1)
1
3
5
7
9
>>> #簡單求值表達式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2)
>>> #交互語句用single
>>> code3 = 'name = input("please input your name:")'
>>> compile3 = compile(code3,'','single')
>>> name #執行前name變量不存在
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
name
NameError: name 'name' is not defined
>>> exec(compile3) #執行時顯示交互命令,提示輸入
please input your name:'pythoner'
>>> name #執行后name變量有值
"'pythoner'"
1-2-2. 輸入輸出相關的函數
print() input
s = input("請輸入內容 : ") #輸入的內容賦值給s變量
print(s) #輸入什么打印什么。數據類型是str
print()輸出
def print(self, *args, sep=' ', end='\n', file=None): # known special case of print
""" print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False) file: 默認是輸出到屏幕,如果設置為文件句柄,輸出到文件 f = open('tmp_file','w') print(123,456,sep=',',file = f,flush=True) sep: 打印多個值之間的分隔符,默認為空格 end: 每一次打印的結尾,默認為換行符 flush: 立即把內容輸出到流文件,不作緩存 """
用print打印一個進度條
import time
for i in range(0,101,2):
time.sleep(0.1)
char_num = i//2 #打印多少個'*'
per_str = '\r%s%% : %s\n' % (i, '*' * char_num) if i == 100 else '\r%s%% : %s'%(i,'*'*char_num)
print(per_str,end='', flush=True)
#小越越 : \r 可以把光標移動到行首但不換行
#Output(動態的):
100% : **************************************************
1-2-3. 數據類型相關
type(o) 返回變量o的數據類型
1-2-4. 內存相關
id(o) o是參數,返回一個變量的內存地址
hash(o) o是參數,返回一個可hash變量的哈希值,不可hash的變量被hash之后會報錯。
t = (1,2,3)
l = [1,2,3]
print(id(t))
print(hash(t)) #可hash
print(hash(l)) #會報錯
Output:
59483960
Traceback (most recent call last):
-378539185
File "D:/Study/BaiduNetdiskDownload/day15課堂筆記/Func.py", line 30, in
print(hash(l)) #會報錯
TypeError: unhashable type: 'list'
hash函數會根據一個內部的算法對當前可hash變量進行處理,返回一個int數字。每一次執行程序,內容相同的變量hash值在這一次執行過程中不會發生改變。
1-2-5. 文件操作相關
open() 打開一個文件,返回一個文件操作符(文件句柄),操作文件的模式有r,w,a,r+,w+,a+
共6種,每一種方式都可以用二進制的形式操作(rb,wb,ab,rb+,wb+,ab+),可以用encoding指定編碼,不在多說。
1-2-6. 模塊操作相關
__import__導入一個模塊
1-2-7. 幫助方法
在控制台執行help()進入幫助模式。可以隨意輸入變量或者變量的類型。輸入q退出
或者直接執行help(o),o是參數,查看和變量o有關的操作。。。
1-2-8. 和調用相關
callable(o),o是參數,看這個變量是不是可調用。 如果o是一個函數名,就會返回True
def func():pass
print(callable(func)) #參數是函數名,可調用,返回True
print(callable(123)) #參數是數字,不可調用,返回False
1-2-9. 查看參數所屬類型的所有內置方法
print(dir(list)) #查看列表的內置方法
print(dir(int)) #查看整數的內置方法
#Output:
['__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']
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
1-3. 和數字相關

數字——數據類型相關:bool,int,float,complex
數字——進制轉換相關:bin,oct,hex
數字——數學運算:abs,divmod,min,max,sum,round,pow
print(bin(10)) #二進制 0b1010
print(oct(10)) #八進制 0o12
print(hex(10)) #十六進制 0xa
print(abs(-5))
print(abs(5))
print(divmod(7,2)) # div出發 mod取余 (3, 1)
print(divmod(9,5)) # 除余 (1, 4)
print(round(3.14159,3)) #3.142
print(pow(2,3)) #pow冪運算 == 2**3
print(pow(3,2))
print(pow(2,3,3)) #冪運算之后再取余 2
print(pow(3,2,1)) # 0
ret = sum([1,2,3,4,5,6])
print(ret) #21
ret = sum([1,2,3,4,5,6,10],)
print(ret) #31
print(min([1,2,3,4]))
print(min(1,2,3,4))
print(min(1,2,3,-4))
print(min(1,2,3,-4,key = abs)) #按絕對值取最小值 1
print(max([1,2,3,4]))
print(max(1,2,3,4))
print(max(1,2,3,-4))
print(max(1,2,3,-4,key = abs)) #按絕對值取最大值 -4
1-4. 和數據結構相關

序列——列表和元組相關的:list和tuple
序列——字符串相關的:str,format,bytes,bytearry,memoryview,ord,chr,ascii,repr
# bytes 轉換成bytes類型
# 我拿到的是gbk編碼的,我想轉成utf-8編碼
print(bytes('你好',encoding='GBK')) # unicode轉換成GBK的bytes
print(bytes('你好',encoding='utf-8')) # unicode轉換成utf-8的bytes
# 網絡編程 只能傳二進制
# 照片和視頻也是以二進制存儲
# html網頁爬取到的也是編碼
b_array = bytearray('你好',encoding='utf-8')
print(b_array)
print(b_array[0])
'\xe4\xbd\xa0\xe5\xa5\xbd'
OutPut:
b'\xc4\xe3\xba\xc3'
b'\xe4\xbd\xa0\xe5\xa5\xbd'
bytearray(b'\xe4\xbd\xa0\xe5\xa5\xbd')
228
序列:reversed,slice
reversed 保留原列表,返回一個反向的迭代器
l = [1,2,3,4,5]
l.reverse()
print(l)
l = [1,2,3,4,5]
l2 = reversed(l)
print(l2)
Output:
[5, 4, 3, 2, 1]
<list_reverseiterator object at 0x014DEEB0>
slice 切片,和[]效果一樣
l = (1,2,23,213,5612,342,43)
sli = slice(1,5,2)
print(l[sli])
print(l[1:5:2])
1-5. 數據集合
字典和集合:dict,set,frozenset
數據集合:len,sorted,enumerate,all,any,zip,filter,map
1-5-1. filter
filter()函數接收一個函數 f 和一個list,這個函數 f 的作用是對每個元素進行判斷,返回 True或
False,filter()根據判斷結果自動過濾掉不符合條件的元素,返回由符合條件元素組成的新list。
例如,要從一個list [1, 4, 6, 7, 9, 12, 17]中刪除偶數,保留奇數,首先,要編寫一個判斷奇數的函數:
def is_odd(x):
return x % 2 == 1
然后,利用filter()過濾掉偶數:
>>>list(filter(is_odd, [1, 4, 6, 7, 9, 12, 17]))
Output:
[1, 7, 9, 17]
利用filter(),可以完成很多有用的功能,例如,刪除 None 或者空字符串:
def is_not_empty(s):
return s and len(s.strip()) > 0
>>>list(filter(is_not_empty, ['test', None, '', 'str', ' ', 'END']))
>>>
結果:
['test', 'str', 'END']
注意: s.strip(rm) 刪除 s 字符串中開頭、結尾處的 rm 序列的字符。當rm為空時,默認刪除空白符(包括'\n', '\r', '\t', ' '),如下:
>>> a = ' 123'
>>> a.strip()
'123'
>>> a = '\t\t123\r\n'
>>> a.strip()
'123'
請利用filter()過濾出1~100中平方根是整數的數,即結果應該是:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
方法:
import math
def is_sqr(x):
return math.sqrt(x) % 1 == 0
print(list(filter(is_sqr, range(1, 101))))
結果:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
1-5-2. map
Python中的map函數應用於每一個可迭代的項,返回的是一個結果list。如果有其他的可迭代參數傳進來,map函數則會把每一個參數都以相應的處理函數進行迭代處理。map()函數接收兩個參數,一個是函數,一個是序列,map將傳入的函數依次作用到序列的每個元素,並把結果作為新的list返回。
有一個list, L = [1,2,3,4],我們要將f(x)=x^2作用於這個list上,那么我們可以使用map函數處理。
>>> L = [1,2,3,4]
>>> def pow2(x):
... return x*x
...
>>> list(map(pow2,L))
[1, 4, 9, 16]
注意:
1 filter 執行了filter之后的結果集合 <= 執行之前的個數,filter只管篩選,不會改變原來的值
2 map 執行前后元素個數不變,值可能發生改變
1-5-3. Sorted
對List、Dict進行排序,Python提供了兩個方法 對給定的List L進行排序,
方法1.用List的成員函數sort進行排序,在本地進行排序,不返回副本
方法2.用built-in函數sorted進行排序(從2.4開始),返回副本,原始輸入不變
sorted(iterable, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customise the sort order, and the
reverse flag can be set to request the result in descending order.
參數說明:
iterable:是可迭代類型;
key:傳入一個函數名,函數的參數是可迭代類型中的每一項,根據函數的返回值大小排序;
reverse:排序規則. reverse = True 降序 或者 reverse = False 升序,有默認值。
返回值:有序列表
列表按照其中每一個值的絕對值排序
l1 = [1,3,5,-2,-4,-6]
l2 = sorted(l1,key=abs)
print(l1)
print(l2)
列表按照每一個元素的len排序
l = [[1,2],[3,4,5,6],(7,),'123']
print(sorted(l,key=len))
注意:和sort的區別
l = [1,-4,6,5,-10]
l.sort(key = abs) # 在原列表的基礎上進行排序
print(l)
print(sorted(l,key=abs,reverse=True)) # 生成了一個新列表 不改變原列表 占內存
print(l)
l = [' ',[1,2],'hello world']
new_l = sorted(l,key=len)
print(new_l)
結果:
[1, -4, 5, 6, -10]
[-10, 6, 5, -4, 1]
[1, -4, 5, 6, -10]
[[1, 2], ' ', 'hello world']