做用域相關:python
locals :函數會以字典的類型返回當前位置的所有局部變量。shell
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}
其餘類型相關:緩存
eval:執行字符串類型的代碼,並返回最終結果。數據結構
print(eval('2+2')) n = 61 print(eval('n + 3')) eval('print(666)')
exec:執行字符串類型的代碼。app
s = ''' for i in [1,2,3]: print(i) ''' exec(s)
compilessh
''' 參數說明: 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。函數
1.2.2輸入輸出相關 input print源碼分析
input:函數接受一個標準輸入數據,返回string類型。ui
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('ddd'))#不可哈希,可變類型 print(hash(123))#可哈希,不可變數據類型。 print(hash((1,2)))#可哈希,不可變數據類型。 print(hash(True))#可哈希,不可變數據類型。 print(hash(False))#可哈希,不可變數據類型。
id(用於獲取對象的內存地址)。
a = 123 #可哈希不可變數據類型 b = 123#可哈希不可變數據類型 print(id(a)) print(id(b)) c = '123'#不可哈希,可變數據類型 d = '123'#不可哈希,可變數據類型 print(id(c)) print(id(d))
文件操做相關:
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
1.2.6調用相關
callable:函數用於檢查一個對象是否可調用的。若是返回True,object仍然可能調用失敗;但若是返回False,調用對象object絕對不會成功。
age = 14 def func1(): print(111) # return 111 age = 15 print(id(age)) print(age) func1() print(id(age)) print(callable(age)) print(callable(func1))
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:內部實際使用了__net__方法,返回迭代器的下一個項目。
iter:函數用來生成迭代器(將一個可迭代對象,生成迭代器)。
# 首先得到Iterator對象: it = iter([1, 2, 3, 4, 5]) # 循環: while True: try: # 得到下一個值: x = next(it) print(x) except StopIteration: # 遇到StopIteration就退出循環 break
from collections import Iterable from collections import Iterator l = [1,2,3] print(isinstance(l,Iterable)) print(isinstance(l,Iterator)) with open('log',encoding='utf-8') as f1: print(isinstance(f1,Iterable)) print(isinstance(f1,Iterator))
進制轉換
bin:將十進制轉換成二進制並返回。
oct:將十進制轉化成八進制字符串並返回。
hex:將十進制轉化成十六進制字符串並返回。
print(bin(100)) print(oct(10)) print(hex(13)) print(hex(18))
數字運算(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爲函數名,經過函數的規則,返回最大值)
a = sum([int(i) for i in input('請輸入數字').split(',')]);print(a) print(sum(range(1,100,2))) print(min([1,3,5,7, -4],key=abs)) #1 print(max([1,3,5,7, -9],key=abs)) #-9
dic = {'a':3,'b':2,'c':1}
print(min(dic,key=lambda x:dic[x]))#c
print(max(dic,key=lambda x:dic[x]))#a
1.4.1數字相關(14)
數據類型(4)
bool:用於將給定參數轉換成bool類型,若是沒有參數,返回False。
int:函數用於講一個字符串或者數字類型轉換爲整形。
float:函數用於將證書和字符串轉換成浮點數。
complex:函數用於建立一個值爲real + imag *j大的負數或者轉化一個字符串或爲輔助。若是第一個參數爲字符串,則不須要指定第二個參數。
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:構造一個切片對象,用於列表的切片
li = ['a','b','c','d','e','f','g'] sl_obj = slice(3) print(li[sl_obj]) sli_obj = slice(0,7,2) print(li[sli_obj])
str1 = 'sfdsfw2gdf'
li = []
a = reversed(str1)
for i in a:
li.append(i)
a1 = ''.join(li)
print(a1)
字符串相關(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 = 'zhangyajie' s1 = s.encode('utf-8') print(s1) s2 = s1.decode('utf-8') print(s2) bs = bytes(s,encoding='utf-8') print(bs) b = '你好'.encode('utf-8');print(b) b1 = b.decode('utf-8');print(b1) print(b1.encode('gbk'))
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))
rd:輸入字符找該字符編碼的位置
chr:輸入位置數字找出其對應的字符
ascii:是ascii碼中的返回該值,不是就返回/u...
print(ord('a')) print(ord('中')) print(chr(97)) print(chr(20013)) print(ascii('a')) print(ascii('中'))
repr:返回一個對象的string形式(原形畢露)
name = 'alex' print('我叫%r' % name) print(repr('{"name":"alex"}')) print(type('{"name":"alex"}'))
數據集合(3)
dict:建立一個字典。
set:建立一個結合。
frozenset:返回一個凍結的集合,凍結後集合不能再添加或刪除任何元素。
set1 = frozenset({1, 2, 3, 'alex'}) print(set1,type(set1))
len:返回一個對象中的元素個數。
sorted:對全部可迭代的對象進行排序操做
L = [('a', 1), ('c', 3), ('d', 4),('b', 2), ] print(sorted(L, key=lambda x:x[1])) students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] print(sorted(students,key=lambda x:x[2])) students = [('john', 'A', 15), ('jane', 'B', 12), ('dave', 'B', 10)] print(sorted(students,key=lambda x:x[1]))
enumerate:枚舉,返回一個枚舉對象。
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,4,5] l2 = ['a','b','c','d','5'] l3 = ('*','**','***','****','*****') for i in zip(l1,l2,l3): print(i)
filter:過濾。篩選
ret = filter(lambda x:x % 2 == 0,y) for i in ret: print(i) ef 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:會根據提供的函數對執行序列作映射。返回一個迭代器
a =map(lambda x:x**2,[1,2,3])
print('__iter__' in dir(a))
print('__next__' in dir(a))
for i in a:
print(i)
匿名函數 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])])
ret = map(lambda x:x**2,[1,5,7,4,8]) for i in ret: print(i)
ret = filter(lambda x:x>10,[5,8,11,9,15]) for i in ret: print(i)