python's fourthday for me 內置函數
阿新 • • 發佈:2018-04-05
加載類 函數返回 排序 文件句柄 最終 編碼 shel 一句話 iterable
locals: 函數會以字典的類型返回當前位置的全部局部變量。
globals: 函數會以字典的了類型返回全部的全局變量。
a = 1 def func(): b = 2 print(locals()) print(globals()) func()
字符串類型的代碼執行:eval, exec, complie
eval: 執行字符串類型的代碼,並返回最終結果。
print(eval(‘2+2‘)) # 4 n = 4 print(eval(‘n+4‘)) # 8 eval(‘print(666)‘) # 666
exec:執行字符串類型的代碼:
s = ‘‘‘for i in [1,2,3]: print(i) ‘‘‘ exec(s) # 1 # 2 # 3
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
輸入輸出相關 input print
input: 函數接受一個標準輸入數據,返回值為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: 默認是輸出到屏幕,如果設置為文件句柄,輸出到文件 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)
內存相關:
hash: 獲取一個對象(可哈希對象:int,str,bool,tuple)的哈希值。
print(hash(123)) # 如果是整型,哈希值就是本身。 print(hash(‘123‘)) # 1234915259760799069 print(hash(True)) # 1 print(hash(False)) # 0 print(hash((1,2,3))) # 2528502973977326415
id:用於獲取對象的內存地址。
print(id(123)) # 1497653856 print(id(‘123‘)) # 2261173251408 print(id(‘abc‘)) # 1573262368136
文件操作相關:
open:函數用於打開一個文件,創建一個 file 對象,相關的方法才可以調用它進行讀寫。
模塊相關:
_import_:函數用於動態加載類和函數。
幫助:
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
callable: 函數用於檢查一個對象是否可調用,如果返回True,object仍然可能調用失敗;但如果返回False,調用對象object絕對不會成功。
>>>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
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‘]
next:內部實際使用了__next__()方法,返回叠代器的下一個項目。
it = iter([1,2,3]) #將列表[1,2,3]將列表轉化成叠代器 while True: try: x = next(it) # 利用循環獲取下一個值 print(x) except Exception: 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(l,Iterable)) # True print(isinstance(l,Iterator)) # True
float:函數用於將整數和字符串轉換成浮點數。
a = 3 b = ‘10‘ print(float(a)) # 3.0 print(float(b)) # 10.0
complex:函數用於創建一個值為 real + imag*j 的復數,或者轉化一個字符串或數為復數。如果第一個參數為字符串,則不需要制定第二個參數。
print(complex(1,2)) # (1+2j) print(complex(1)) # (1+0j) print(complex(‘1‘)) # (1+0j) print(complex(‘1+2j‘)) # (1+2j) ## 註意:這個地方在"+"號兩邊不能有空格,也就是不能寫成"1 + 2j",\應該是"1+2j",否則會報錯 print(complex(1+2j)) # (1+2j)
進制之間的轉換:
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‘>
數學運算:
abs:函數返回數字的絕對值。
divmod:計算除數與被除數的結果,返回一個包含商和余數的元祖。(a//b,a%b)
round:保留浮點數的小數位數,默認保留整數。
pow:求x**y次冪,(三個參數為x**y的結果對z求余)
print(abs(-5)) #5 print(divmod(8,3)) #(2,2) print(round(3.1415,2)) # 3.14 print(pow(2,3)) # 8 print(pow(2,3,3)) # 2
sum:對可叠代對象進行求和運算。(可設初始值)
min:返回可叠代對象的最小值(可加key,key為函數名,通過函數的規則,返回最小值)
max:返回可叠代對象的最大值(可加key,key為函數名,通過函數規則,返回最大值)
l = [1,2,3] print(sum(l)) # 6 print(max(l)) # 3 print(min(l)) # 1
reversed:將一個序列翻轉,並返回該反轉序列的叠代器。
l = [1,2,3] l2 = reversed(l) print(l2) # # <list_reverseiterator object at 0x000002703CACF2E8> print(‘__iter__‘in dir(l2)) # True print(‘__next__‘in dir(l2)) # True
slice:構造一個切片對象,用於列表的切片。
l1 = [1,2,3,4,5] l2 = [‘1‘,‘2‘,‘3‘,‘4‘,‘5‘] sli_l = slice(3) # 相當從索引0切到3不包括3. print(l1[sli_l]) # [1, 2, 3] print(l2[sli_l]) # [‘1‘, ‘2‘, ‘3‘]
format:與具體數據相關,用於精算。
print(format(‘顧清秋‘,‘<30‘)) #左對齊 print(format(‘顧清秋‘,‘^30‘)) # 居中 print(format(‘顧清秋‘,‘>30‘)) # 右對齊 # 顧清秋 # 顧清秋 # 顧清秋
bytes:用於不同編碼之間的轉化。
s = ‘顧清秋‘ bs1 = s.encode(‘utf-8‘) print(bs1) # b‘\xe9\xa1\xbe\xe6\xb8\x85\xe7\xa7\x8b‘ bs2 = bytes(s,encoding=‘utf-8‘) print(bs2) # b‘\xe9\xa1\xbe\xe6\xb8\x85\xe7\xa7\x8b‘
bytearry:返回一個新字節數組。這個數組裏的元素是可變的,並且每個元素的值返回: 0 <= x <256
ret = bytearray(‘alex‘,encoding=‘utf-8‘) print(ret) # bytearray(b‘alex‘) print(id(ret)) # 2250540703504 print(ret[0]) # 97 (‘a‘ = 97) ret[0] = 65 print(ret) # bytearray(b‘Alex‘) (‘A‘ = 65)
memoryview:
ret = memoryview(‘顧清秋‘.encode(‘utf-8‘)) print(len(ret)) # 9 #字節長度 print(ret) # <memory at 0x000001D9447DD1C8> print(bytes(ret[:3]).decode(‘utf-8‘)) # 顧
ord:輸入字符找該字符編碼的位置。 unicode
chr:輸入數字找出其對應的字符。 unicode
ascii:是ASCII中的就返回值,不是就返回\u...
print(ord(‘a‘)) # 97 print(ord(‘中‘)) # 20013 print(chr(97)) # ‘a‘ print(chr(20013)) # ‘中‘ print(ascii(‘a‘)) # ‘a‘ print(ascii(‘中‘)) # ‘\u4e2d‘
repr:返回一個對象的str形式。
print(repr(‘{"顧清秋"}‘)) # ‘{"顧清秋"}‘
sorted:對所由可叠代對象進行排序操作。
l = [1,8,3,5,4,9] l2 = sorted(l) l3 = sorted(l,reverse=True) print(l2) # [1, 3, 4, 5, 8, 9] print(l3) # [9, 8, 5, 4, 3, 1]
enumerate:枚舉,返回一個枚舉對象。
l = [‘a‘,‘b‘,‘c‘] print(enumerate(l)) for i in enumerate(l,1): print(i,type(i)) for k,v in enumerate(l,1): print(k,v) # (1, ‘a‘) <class ‘tuple‘> # (2, ‘b‘) <class ‘tuple‘> # (3, ‘c‘) <class ‘tuple‘> # 1 a # 2 b # 3 c
all:可叠代對象中,全都是True才是True.
any:可叠代對象中,有一個True就是True.
print(all([1,2,True,0])) # False print(any([0,False,1,‘‘])) # True
zip:函數用於將可叠代的對象作為參數,將對相對應的元素打包成一個個元祖,然後返回由這些元祖,如果各個叠代器的元素不一致,則返回列表長度與最短的對象相同。
l1 = [1,2,3] l2 = [‘a‘,‘b‘,‘c‘,‘d‘] l3 = (‘*‘,‘**‘,‘***‘) l4 = zip(l1,l2,l3) for i in l4: print(i) # (1, ‘a‘, ‘*‘) # (2, ‘b‘, ‘**‘) # (3, ‘c‘, ‘***‘)
filter:過濾,通過你的函數,過濾一個可叠代對象,返回的是True
def func(x): return x % 2 == 0 ret = filter(func,[1,2,3,4,5,6]) # 通過一個函數,過濾一個可叠代對象返回的是叠代器。 print(‘__iter__‘in dir(ret)) # True print(‘__next__‘in dir(ret)) # True # print(ret.__next__()) # 2 for i in ret: print(i) # 2 # 4 # 6
map:會根據提供的函數對指定序列做映射。
def func(x): return x**2 ret = map(func,[1,2,3,4]) for i in ret: print(i) # 1 # 4 # 9 # 16 l1 = [1,3,5,7,9] l2 = [2,4,6,8,10] ret = map(lambda x,y:x+y,l1,l2) for i in ret: print(i) # 3 # 7 # 11 # 15 # 19
匿名函數:為了解決那些功能很簡單的需求而設計的一句話函數。
def cal(n): return n**n print(cal(2)) # 4 # 換成匿名函數 cal = lambda n:n**n print(cal(2)) # 4
匿名函數的格式:
函數名 = lambda 參數 :返回值
1,參數可以有多個,用逗號隔開。
2,匿名函數不管邏輯多復雜,只能寫一行,且邏輯執行結束後的內容就是返回值。
3,返回值和正常函數一樣可以是任意數據類型。
匿名函數並不是真的不能有名字。
匿名函數的調用和正常的調用也沒什麽分別,就是函數名(參數)就可以了...
匿名函數與內置函數舉例:
l = [3,2,100,123] print(max(l)) # 123 dic = {‘k1‘:10,‘k2‘:30,‘k3‘:20} print(max(dic)) # k3 print(dic[max(dic,key = lambda x:dic[x])]) # 30View Code
res = map(lambda x:x**2,[1,2,3]) for i in res: print(i) # 1 # 4 # 9View Code
res = filter(lambda x:x>3,[1,2,3,4,5]) for i in res: print(i) # 4 # 5View Code
python's fourthday for me 內置函數