總結day13 ----內建函式
內建函式
我們一起來看看python裡的內建函式。什麼是內建函式?就是Python給你提供的,拿來直接用的函式,比如print,input等等。截止到python版本3.6.2,現在python一共為我們提供了68個內建函式。它們就是python提供給你直接可以拿來使用的所有函式。這些函式有些我們已經用過了,有些我們還沒用到過,還有一些是被封印了,必須等我們學了新知識才能解開封印的。那今天我們就一起來認識一下python的內建函式。這麼多函式,我們該從何學起呢?
內建函式 | ||||
abs() | dict() | help() | min() | setattr() |
all() | dir() | hex() | next() | slice() |
any() | divmod() | id() | object() | sorted() |
ascii() | enumerate() | input() | oct() | staticmethod() |
bin() | eval() | int() | open() | str() |
bool() | exec() | isinstance() | ord() | sum() |
bytearray() | filter() | issubclass() | pow() | super() |
bytes() | float() | iter() | print() | tuple() |
callable() | format() | len() | property() | type() |
chr() | frozenset() | list() | range() | vars() |
classmethod() | getattr() | locals() | repr() | zip() |
compile() | globals() | map() | reversed() | __import__() |
complex() | hasattr() | max() | round() | |
delattr() | hash() | memoryview() | set() |
1.1作用域相關
locals :函式會以字典的型別返回當前位置的全部區域性變數。
globals:函式以字典的型別返回全部全域性變數。
a = 1 b = 2 print(locals()) print(globals()) # 這兩個一樣,因為是在全域性執行的。 ########################## def func(argv): c = 2 print(locals()) print(globals()) func(3) #這兩個不一樣,locals() {'argv': 3, 'c': 2} #globals() {'__doc__': None, '__builtins__': <module 'builtins' (built-in)>, '__cached__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000024409148978>, '__spec__': None, '__file__': 'D:/lnh.python/.../內建函式.py', 'func': <function func at 0x0000024408CF90D0>, '__name__': '__main__', '__package__': None}程式碼示例
1.2其他相關
1.2.1 字串型別程式碼的執行 eval,exec,complie
eval:執行字串型別的程式碼,並返回最終結果。
eval('2 + 2') # 4 n=81 eval("n + 4") # 85 eval('print(666)') # 666View Code
exec:執行字串型別的程式碼。
s = ''' for i in [1,2,3]: print(i) ''' exec(s)View Code
compile:將字串型別的程式碼編譯。程式碼物件能夠通過exec語句來執行或者eval()進行求值。
''' 引數說明: 1. 引數source:字串或者AST(Abstract Syntax Trees)物件。即需要動態執行的程式碼段。 2. 引數 filename:程式碼檔名稱,如果不是從檔案讀取程式碼則傳遞一些可辨認的值。當傳入了source引數時,filename引數傳入空字元即可。 3. 引數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) >>> #簡單求值表示式用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'"View Code
有返回值的字串形式的程式碼用eval,沒有返回值的字串形式的程式碼用exec,一般不用compile。
1.2.2 輸入輸出相關 input,print
input:函式接受一個標準輸入資料,返回為 string 型別。
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: 預設是輸出到螢幕,如果設定為檔案控制代碼,輸出到檔案 sep: 列印多個值之間的分隔符,預設為空格 end: 每一次列印的結尾,預設為換行符 flush: 立即把內容輸出到流檔案,不作快取 """ ''' print(111,222,333,sep='*') # 111*222*333 print(111,end='') print(222) #兩行的結果 111222 f = open('log','w',encoding='utf-8') print('寫入檔案',file=f,flush=True)View Code
1.2.3記憶體相關 hash id
hash:獲取一個物件(可雜湊物件:int,str,Bool,tuple)的雜湊值。
print(hash(12322)) print(hash('123')) print(hash('arg')) print(hash('alex')) print(hash(True)) print(hash(False)) print(hash((1,2,3))) ''' 12322 -2996001552409009098 -4637515981888139739 2311495795356652852 1 0 2528502973977326415 '''View Code
id:用於獲取物件的記憶體地址。
print(id(123)) # 1674055952 print(id('abc')) # 2033192957072View Code
1.2.3檔案操作相關
open:函式用於開啟一個檔案,建立一個 file 物件,相關的方法才可以呼叫它進行讀寫。
1.2.4模組相關__import__
__import__:函式用於動態載入類和函式 。
1.2.5幫助
help:函式用於檢視函式或模組用途的詳細說明。
print(help(list)) Help on class list in module builtins: class list(object) | list() -> new empty list | list(iterable) -> new list initialized from iterable's items | | Methods defined here: | | __add__(self, value, /) | Return self+value. | | __contains__(self, key, /) | Return key in self. | | __delitem__(self, key, /) | Delete self[key]. | | __eq__(self, value, /) | Return self==value. | | __ge__(self, value, /) | Return self>=value. | | __getattribute__(self, name, /) | Return getattr(self, name). | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __gt__(self, value, /) | Return self>value. | | __iadd__(self, value, /) | Implement self+=value. | | __imul__(self, value, /) | Implement self*=value. | | __init__(self, /, *args, **kwargs) | Initialize self. See help(type(self)) for accurate signature. | | __iter__(self, /) | Implement iter(self). | | __le__(self, value, /) | Return self<=value. | | __len__(self, /) | Return len(self). | | __lt__(self, value, /) | Return self<value. | | __mul__(self, value, /) | Return self*value.n | | __ne__(self, value, /) | Return self!=value. | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. | | __repr__(self, /) | Return repr(self). | | __reversed__(...) | L.__reversed__() -- return a reverse iterator over the list | | __rmul__(self, value, /) | Return self*value. | | __setitem__(self, key, value, /) | Set self[key] to value. | | __sizeof__(...) | L.__sizeof__() -- size of L in memory, in bytes | | append(...) | L.append(object) -> None -- append object to end | | clear(...) | L.clear() -> None -- remove all items from L | | copy(...) | L.copy() -> list -- a shallow copy of L | | count(...) | L.count(value) -> integer -- return number of occurrences of value | | extend(...) | L.extend(iterable) -> None -- extend list by appending elements from the iterable | | index(...) | L.index(value, [start, [stop]]) -> integer -- return first index of value. | Raises ValueError if the value is not present. | | insert(...) | L.insert(index, object) -- insert object before index | | pop(...) | L.pop([index]) -> item -- remove and return item at index (default last). | Raises IndexError if list is empty or index is out of range. | | remove(...) | L.remove(value) -> None -- remove first occurrence of value. | Raises ValueError if the value is not present. | | reverse(...) | L.reverse() -- reverse *IN PLACE* | | sort(...) | L.sort(key=None, reverse=False) -> None -- stable sort *IN PLACE* | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None None Process finished with exit code 0View Code
1.2.6呼叫相關
callable:函式用於檢查一個物件是否是可呼叫的。如果返回True,object仍然可能呼叫失敗;但如果返回False,呼叫物件ojbect絕對不會成功。
>>>callable(0) False >>> callable("runoob") False >>> def add(a, b): ... return a + b ... >>> callable(add) # 函式返回 True True >>> class A: # 類 ... def method(self): ... return 0 ... >>> callable(A) # 類返回 True True >>> a = A() >>> callable(a) # 沒有實現 __call__, 返回 False False >>> class B: ... def __call__(self): ... return 0 ... >>> callable(B) True >>> b = B() >>> callable(b) # 實現 __call__, 返回 TrueView Code
1.2.7檢視內建屬性
dir:函式不帶引數時,返回當前範圍內的變數、方法和定義的型別列表;帶引數時,返回引數的屬性、方法列表。如果引數包含方法__dir__(),該方法將被呼叫。如果引數不包含__dir__(),該方法將最大限度地收集引數資訊。
>>>dir() # 獲得當前模組的屬性列表 ['__builtins__', '__doc__', '__name__', '__package__', 'arr', 'myslice'] >>> dir([ ]) # 檢視列表的方法 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__setslice__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']View Code
1.3 迭代器生成器相關
range:函式可建立一個整數物件,一般用在 for 迴圈中。
next:內部實際使用了__next__方法,返回迭代器的下一個專案。
# 首先獲得Iterator物件: it = iter([1, 2, 3, 4, 5]) # 迴圈: while True: try: # 獲得下一個值: x = next(it) print(x) except StopIteration: # 遇到StopIteration就退出迴圈 breakView Code
iter:函式用來生成迭代器(講一個可迭代物件,生成迭代器)。
from collections import Iterable from collections import Iterator l = [1,2,3] print(isinstance(l,Iterable)) # True print(isinstance(l,Iterator)) # False l1 = iter(l) print(isinstance(l1,Iterable)) # True print(isinstance(l1,Iterator)) # TrueView Code
1.4 基礎資料型別相關
1.4.1數字相關(14)
資料型別(4):
bool :用於將給定引數轉換為布林型別,如果沒有引數,返回 False。
int:函式用於將一個字串或數字轉換為整型。
print(int()) # 0 print(int('12')) # 12 print(int(3.6)) # 3 print(int('0100',base=2)) # 將2進位制的 0100 轉化成十進位制。結果為 4View Code
float:函式用於將整數和字串轉換成浮點數。
complex:函式用於建立一個值為 real + imag * j 的複數或者轉化一個字串或數為複數。如果第一個引數為字串,則不需要指定第二個引數。。
>>>complex(1, 2) (1 + 2j) >>> complex(1) # 數字 (1 + 0j) >>> complex("1") # 當做字串處理 (1 + 0j) # 注意:這個地方在"+"號兩邊不能有空格,也就是不能寫成"1 + 2j",應該是"1+2j",否則會報錯 >>> complex("1+2j") (1 + 2j)View Code
進位制轉換(3):
bin:將十進位制轉換成二進位制並返回。
oct:將十進位制轉化成八進位制字串並返回。
hex:將十進位制轉化成十六進位制字串並返回。
print(bin(10),type(bin(10))) # 0b1010 <class 'str'> print(oct(10),type(oct(10))) # 0o12 <class 'str'> print(hex(10),type(hex(10))) # 0xa <class 'str'>View Code
數學運算(7):
abs:函式返回數字的絕對值。
divmod:計算除數與被除數的結果,返回一個包含商和餘數的元組(a // b, a % b)。
round:保留浮點數的小數位數,預設保留整數。
pow:求x**y次冪。(三個引數為x**y的結果對z取餘)
print(abs(-5)) # 5 print(divmod(7,2)) # (3, 1) print(round(7/3,2)) # 2.33 print(round(7/3)) # 2 print(round(3.32567,3)) # 3.326 print(pow(2,3)) # 兩個引數為2**3次冪 print(pow(2,3,3)) # 三個引數為2**3次冪,對3取餘。View Code
sum:對可迭代物件進行求和計算(可設定初始值)。
min:返回可迭代物件的最小值(可加key,key為函式名,通過函式的規則,返回最小值)。
max:返回可迭代物件的最大值(可加key,key為函式名,通過函式的規則,返回最大值)。
print(sum([1,2,3])) print(sum((1,2,3),100)) print(min([1,2,3])) # 返回此序列最小值 ret = min([1,2,-5,],key=abs) # 按照絕對值的大小,返回此序列最小值 print(ret) dic = {'a':3,'b':2,'c':1} print(min(dic,key=lambda x:dic[x])) # x為dic的key,lambda的返回值(即dic的值進行比較)返回最小的值對應的鍵 print(max([1,2,3])) # 返回此序列最大值 ret = max([1,2,-5,],key=abs) # 按照絕對值的大小,返回此序列最大值 print(ret) dic = {'a':3,'b':2,'c':1} print(max(dic,key=lambda x:dic[x])) # x為dic的key,lambda的返回值(即dic的值進行比較)返回最大的值對應的鍵View Code
1.4.2和資料結構相關(24)
列表和元祖(2)
list:將一個可迭代物件轉化成列表(如果是字典,預設將key作為列表的元素)。
tuple:將一個可迭代物件轉化成元祖(如果是字典,預設將key作為元祖的元素)。
l = list((1,2,3)) print(l) l = list({1,2,3}) print(l) l = list({'k1':1,'k2':2}) print(l) tu = tuple((1,2,3)) print(tu) tu = tuple([1,2,3]) print(tu) tu = tuple({'k1':1,'k2':2}) print(tu)View Code
相關內建函式(2)
reversed:將一個序列翻轉,並返回此翻轉序列的迭代器。
slice:構造一個切片物件,用於列表的切片。
ite = reversed(['a',2,3,'c',4,2]) for i in ite: print(i) li = ['a','b','c','d','e','f','g'] sli_obj = slice(3) print(li[sli_obj]) sli_obj = slice(0,7,2) print(li[sli_obj])View Code
字串相關(9)
str:將資料轉化成字串。
format:與具體資料相關,用於計算各種小數,精算等。
#字串可以提供的引數,指定對齊方式,<是左對齊, >是右對齊,^是居中對齊 print(format('test', '<20')) print(format('test', '>20')) print(format('test', '^20')) #整形數值可以提供的引數有 'b' 'c' 'd' 'o' 'x' 'X' 'n' None >>> format(3,'b') #轉換成二進位制 '11' >>> format(97,'c') #轉換unicode成字元 'a' >>> format(11,'d') #轉換成10進位制 '11' >>> format(11,'o') #轉換成8進位制 '13' >>> format(11,'x') #轉換成16進位制 小寫字母表示 'b' >>> format(11,'X') #轉換成16進位制 大寫字母表示 'B' >>> format(11,'n') #和d一樣 '11' >>> format(11) #預設和d一樣 '11' #浮點數可以提供的引數有 'e' 'E' 'f' 'F' 'g' 'G' 'n' '%' None >>> format(314159267,'e') #科學計數法,預設保留6位小數 '3.141593e+08' >>> format(314159267,'0.2e') #科學計數法,指定保留2位小數 '3.14e+08' >>> format(314159267,'0.2E') #科學計數法,指定保留2位小數,採用大寫E表示 '3.14E+08' >>> format(314159267,'f') #小數點計數法,預設保留6位小數 '314159267.000000' >>> format(3.14159267000,'f') #小數點計數法,預設保留6位小數 '3.141593' >>> format(3.14159267000,'0.8f') #小數點計數法,指定保留8位小數 '3.14159267' >>> format(3.14159267000,'0.10f') #小數點計數法,指定保留10位小數 '3.1415926700' >>> format(3.14e+1000000,'F') #小數點計數法,無窮大轉換成大小字母 'INF' #g的格式化比較特殊,假設p為格式中指定的保留小數位數,先嚐試採用科學計數法格式化,得到冪指數exp,如果-4<=exp<p,則採用小數計數法,並保留p-1-exp位小數,否則按小數計數法計數,並按p-1保留小數位數 >>> format(0.00003141566,'.1g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學計數法計數,保留0位小數點 '3e-05' >>> format(0.00003141566,'.2g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學計數法計數,保留1位小數點 '3.1e-05' >>> format(0.00003141566,'.3g') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學計數法計數,保留2位小數點 '3.14e-05' >>> format(0.00003141566,'.3G') #p=1,exp=-5 ==》 -4<=exp<p不成立,按科學計數法計數,保留0位小數點,E使用大寫 '3.14E-05' >>> format(3.1415926777,'.1g') #p=1,exp=0 ==》 -4<=exp<p成立,按小數計數法計數,保留0位小數點 '3' >>> format(3.1415926777,'.2g') #p=1,exp=0 ==》 -4<=exp<p成立,按小數計數法計數,保留1位小數點 '3.1' >>> format(3.1415926777,'.3g') #p=1,exp=0 ==》 -4<=exp<p成立,按小數計數法計數,保留2位小數點 '3.14' >>> format(0.00003141566,'.1n') #和g相同 '3e-05' >>> format(0.00003141566,'.3n') #和g相同 '3.14e-05' >>> format(0.00003141566) #和g相同 '3.141566e-05'View Code
bytes:用於不同編碼之間的轉化。
# s = '你好' # bs = s.encode('utf-8') # print(bs) # s1 = bs.decode('utf-8') # print(s1) # bs = bytes(s,encoding='utf-8') # print(bs) # b = '你好'.encode('gbk') # b1 = b.decode('gbk') # print(b1.encode('utf-8'))View Code
bytearry:返回一個新位元組陣列。這個數組裡的元素是可變的,並且每個元素的值範圍: 0 <= x < 256。
ret = bytearray('alex',encoding='utf-8') print(id(ret)) print(ret) print(ret[0]) ret[0] = 65 print(ret) print(id(ret))View Code
memoryview
ret = memoryview(bytes('你好',encoding='utf-8')) print(len(ret)) print(ret) print(bytes(ret[:3]).decode('utf-8')) print(bytes(ret[3:]).decode('utf-8'))View Code
ord:輸入字元找該字元編碼的位置
chr:輸入位置數字找出其對應的字元
ascii:是ascii碼中的返回該值,不是就返回/u...
# ord 輸入字元找該字元編碼的位置 # print(ord('a')) # print(ord('中')) # chr 輸入位置數字找出其對應的字元 # print(chr(97)) # print(chr(20013)) # 是ascii碼中的返回該值,不是就返回/u... # print(ascii('a')) # print(ascii('中'))View Code
repr:返回一個物件的string形式(原形畢露)。
# %r 原封不動的寫出來 # name = 'taibai' # print('我叫%r'%name) # repr 原形畢露 print(repr('{"name":"alex"}')) print('{"name":"alex"}')View Code
資料集合(3)
dict:建立一個字典。
set:建立一個集合。
frozenset:返回一個凍結的集合,凍結後集合不能再新增或刪除任何元素。
相關內建函式(8)
len:返回一個物件中元素的個數。
sorted:對所有可迭代的物件進行排序操作。
L = [('a', 1), ('c', 3), ('d', 4),('b', 2), ] sorted(L, key=lambda x:x[1]) # 利用key [('a', 1), ('b', 2), ('c', 3), ('d', 4)] students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] sorted(students, key=lambda s: s[2]) # 按年齡排序 [('dave', 'B', 10), ('jane', 'B', 12), ('john', 'A', 15)] sorted(students, key=lambda s: s[2], reverse=True) # 按降序 [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)]View Code
enumerate:列舉,返回一個列舉物件。
print(enumerate([1,2,3])) for i in enumerate([1,2,3]): print(i) for i in enumerate([1,2,3],100): print(i)View Code
all:可迭代物件中,全都是True才是True
any:可迭代物件中,有一個True 就是True
# all 可迭代物件中,全都是True才是True # any 可迭代物件中,有一個True 就是True # print(all([1,2,True,0])) # print(any([1,'',0]))View Code
zip:函式用於將可迭代的物件作為引數,將物件中對應的元素打包成一個個元組,然後返回由這些元組組成的列表。如果各個迭代器的元素個數不一致,則返回列表長度與最短的物件相同。
l1 = [1,2,3,] l2 = ['a','b','c',5] l3 = ('*','**',(1,2,3)) for i in zip(l1,l2,l3): print(i)View Code
filter:過濾·。
#filter 過濾 通過你的函式,過濾一個可迭代物件,返回的是True #類似於[i for i in range(10) if i > 3] # def func(x):return x%2 == 0 # ret = filter(func,[1,2,3,4,5,6,7]) # print(ret) # for i in ret: # print(i)View Code
map:會根據提供的函式對指定序列做對映。
>>>def square(x) : # 計算平方數 ... return x ** 2 ... >>> map(square, [1,2,3,4,5]) # 計算列表各個元素的平方 [1, 4, 9, 16, 25] >>> map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # 使用 lambda 匿名函式 [1, 4, 9, 16, 25] # 提供了兩個列表,對相同位置的列表資料進行相加 >>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]) [3, 7, 11, 15, 19]View Code
匿名函式
匿名函式:為了解決那些功能很簡單的需求而設計的一句話函式。
#這段程式碼 def calc(n): return n**n print(calc(10)) #換成匿名函式 calc = lambda n:n**n print(calc(10))
上面是我們對calc這個匿名函式的分析,下面給出了一個關於匿名函式格式的說明
函式名 = lambda 引數 :返回值 #引數可以有多個,用逗號隔開 #匿名函式不管邏輯多複雜,只能寫一行,且邏輯執行結束後的內容就是返回值 #返回值和正常的函式一樣可以是任意資料型別
我們可以看出,匿名函式並不是真的不能有名字。
匿名函式的呼叫和正常的呼叫也沒有什麼分別。 就是 函式名(引數) 就可以了~~~
匿名函式與內建函式舉例:
l=[3,2,100,999,213,1111,31121,333] print(max(l)) dic={'k1':10,'k2':100,'k3':30} print(max(dic)) print(dic[max(dic,key=lambda k:dic[k])])View Code
res = map(lambda x:x**2,[1,5,7,4,8]) for i in res: print(i)View Code
res = filter(lambda x:x>10,[5,8,11,9,15]) for i in res: print(i)View Code