內置函數
我們一起來看看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)') # 666
exec:執行字符串類型的代碼。

s = ''' for i in [1,2,3]: print(i) ''' exec(s)
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'"
有返回值的字符串形式的代碼用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)
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 '''
id:用於獲取對象的內存地址。

print(id(123)) # 1674055952 print(id('abc')) # 2033192957072
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 0
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__, 返回 True
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']
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就退出循環 break
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)) # True
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 轉化成十進制。結果為 4
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)
進制轉換(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'>
數學運算(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取余。
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的值進行比較)返回最大的值對應的鍵
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)
相關內置函數(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])
字符串相關(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'
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'))
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))
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'))
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('中'))
repr:返回一個對象的string形式(原形畢露)。

# %r 原封不動的寫出來 # name = 'taibai' # print('我叫%r'%name) # repr 原形畢露 print(repr('{"name":"alex"}')) print('{"name":"alex"}')
數據集合(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)]
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)
all:可迭代對象中,全都是True才是True
any:可迭代對象中,有一個True 就是True

# all 可迭代對象中,全都是True才是True # any 可迭代對象中,有一個True 就是True # print(all([1,2,True,0])) # print(any([1,'',0]))
zip:函數用於將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然后返回由這些元組組成的列表。如果各個迭代器的元素個數不一致,則返回列表長度與最短的對象相同。

l1 = [1,2,3,] l2 = ['a','b','c',5] l3 = ('*','**',(1,2,3)) for i in zip(l1,l2,l3): print(i)
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)
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]
匿名函數
匿名函數:為了解決那些功能很簡單的需求而設計的一句話函數。
#這段代碼 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])])

res = map(lambda x:x**2,[1,5,7,4,8]) for i in res: print(i)

res = filter(lambda x:x>10,[5,8,11,9,15]) for i in res: print(i)