1.abs()
取數字的絕對值,參數可以是整數或浮點數。如果參數是一個復數,則返回其大小
>>> print(abs(-28)) 28 >>> print(abs(-2.34)) 2.34 >>> print(abs(1/3)) 0.3333333333333333
2.dict()
用於創建字典
>>> dict() #創建空字典 {} >>> dict(a='who',b='while',c='whit') #傳入關鍵字創建字典 {'b': 'while', 'c': 'whit', 'a': 'who'} >>> dict(zip([1,2,3],['one','two','three'])) #映射函數方式創建字典 {1: 'one', 2: 'two', 3: 'three'} >>> dict([(1,'one'),(2,'two'),(3,'three')]) #可迭代對象方式創建字典 {1: 'one', 2: 'two', 3: 'three'}
3.help()
用於查看函數或模塊用途的詳細說明
>>> help('sys') #查看sys模塊的幫助 >>> help('str') #查看str數據類型幫助信息 >>> a = [1,2,3] >>> help(a) #查看列表list幫助信息 >>> help(a.extend) #顯示list的extend方法的幫助信息
4.min()
返回給定參數的最小值,參數可以為列表,元組,字典和集合
>>> print(min(1,23,4)) #給定序列的最小值,這里實際上判斷的元組類 1 >>> print(min([1,2,3,4])) #列表 1 >>> print(min((3,4,5))) #元組 3 >>> print(min({'a':3,'b':44,'c':22})) #字典,對字符串按ascii碼位置判斷 a >>> print(min({22,33,44})) #集合判斷 22
5.setattr()
對應函數 getatt(),用於設置屬性值,該屬性必須存在,參數是一個對象,一個字符串和一個任意值。該字符串可以命名現有的屬性或新的屬性。如果該對象允許,該函數將該值分配給該屬性。
>>> class x(object): ... def aa(): ... print('test is aa') ... >>> setattr(x,'foo',123) >>> print(x.foo) 123
6.all()
判斷給定的可迭代參數中所有元素不為0,空,False,返回True,否則返回False
>>> all([1,2,3]) #列表元素不為空或0返回True True >>> all([0,2,3]) #列表元素為0返回False False >>> all([1,'',3]) #列表元素為空返回False False >>> all([1,False,3]) #列表元素為False返回False False >>> all([]) #注意:空列表返回True True >>> all((1,2,3)) #元組元素都不為空或0返回True True >>> all((0,2,3)) #為0返回False False >>> all((1,'',3)) #為空返回False False >>> all(()) #注意:空元組返回True True >>> all((1,False,3)) #為False返回False False
7.dir()
獲取當前范圍內的變量,方法和定義的類型列表,帶參數時返回參數的屬性,方法列表
>>> dir() #獲取當前范圍內的變量,方法和定義的類型列表, ['__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'd1'] #帶參數時返回參數的屬性,方法列表 >>> dir(list) #返回列表的方法 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__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']
8.hex()
將數值轉換成十六進制
>>> hex(16) #將十進制轉換成十六進制 '0x10' >>> hex(-17) '-0x11' >>> hex(0o11) #將八進制轉換成十六進制 '0x9' >>> hex(0b1100) #將二進制轉換成十六直接 '0xc' >>> hex(0b10) '0x2' #說明:二進制表示(0b),八進制表示(0o),十六進制(0x)
9.next()
返回迭代器的下一個項目,可在沒有下一個項目時返回設置的默認值
>>> it = iter([1,2,3,4,5]) #使用iter生成迭代器 >>> next(it) #返回一個可迭代數據結構中的下一個元素 1 >>> next(it) 2 >>> next(it) 3 >>> next(it) 4 >>> next(it) 5 >>> next(it) #在沒有下一個元素則會觸發 StopIteration 異常 Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration >>> next(it,'no values') #在沒有下一個元素時返回指定默認值 'no values'
10.slice()
用來創建切片對象,可指定起始和結束位置,間隔
class slice(stop)
class slice(start,stop[,step])
>>> l1 = [1,2,3,4,5,6,7,8] >>> slice1 = slice(5) #定義一個切片對象,截取長度為5,不指定起始位置默認從索引0開始 >>> l1[slice1] #列表引用切片對象 [1, 2, 3, 4, 5] >>> slice3 = slice(1,6,1) #定義一個切片對象,指定起始位置為1結束位置為6,間隔為1 >>> l1[slice3] #當間隔為1時,相當於0間隔 [2, 3, 4, 5, 6] >>> slice2 = slice(1,7,2) #間隔為2時,相隔一個截取元素 >>> l1[slice2] [2, 4, 6]
11.any()
判斷可迭代參數是否全部為空或0或False則返回False,否則返回True。
>>> any([1,2,3]) True >>> any([0,'',1]) True >>> any([0,'',False]) #全部為空值才返回False False >>> any([]) #空列表返回False False >>> any((1,2,3)) True >>> any((0,'',1)) True >>> any((0,'',False)) False >>> any(()) #空元組返回False False
12.divmod(a,b)
返回a除以b的商和余數的元組(a//b,a%b)
>>> divmod(4,2) #返回4除以2的商和余數 (2, 0) >>> divmod(15,4) (3, 3) >>> divmod(2+0.2j,3+1.3j) #不支持負數 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can't take floor or mod of complex number. >>> divmod(4,8) #當不被整除時余數返回4,不解! (0, 4) >>> divmod(4,9) (0, 4) >>> divmod(4,100) (0, 4)
13.id()
用於獲取對象的內存地址
>>> id(1) 8956480 >>> id(2) 8956512 >>> id('b') 140349300904040 >>> a = 'python' >>> id(a) 140349300975744
14.object()
獲取一個新的,無特性(geatureless)對象。Object是所有類的基類。它提供的方法將在所有的類型實例中共享。
該函數時2.2.版本新增,2.3版本之后,該函數不接受任何參數。
15.sorted()
對所有可迭代的對象進行排序操作
sort 與 sorted 區別:
sort 是應用在 list 上的方法,sorted 可以對所有可迭代的對象進行排序操作。
list 的 sort 方法返回的是對已經存在的列表進行操作,而內建函數 sorted 方法返回的是一個新的 list,而不是在原來的基礎上進行的操作。
語法:sorted(iterable, /, *, key=None, reverse=False)
iterable:可迭代對象
key:用來進行比較的元素,只有一個參數,指定可迭代對象中的一個元素來進行排序
reverse:排序規則,reverse=True為降序,reverse= False為升序(默認)
>>> sorted([-12,3,23,18]) #列表按數字排序 [-12, 3, 18, 23] >>> sorted([-12,3,23,18],key=abs) #列表數字按絕對值排序 [3, -12, 18, 23] >>> sorted(['bc','aa','fd','cj']) #列表字符按首字母的ASCII碼排序 ['aa', 'bc', 'cj', 'fd'] #如果是數字與字符混合,在python3需要指定key的函數對象 >>> l1 = [2,'a','b',4,-33,'python'] >>> l1 [2, 'a', 'b', 4, -33, 'python'] >>> sorted(l1,key=id) #按內存地址排序 [2, 4, -33, 'a', 'b', 'python'] >>> sorted(l1,key=str) #按字符串排序,對所有數據轉換成字符串后首個字符按ASCII排序 [-33, 2, 4, 'a', 'b', 'python'] >>> ord('-') 45 >>> ord('2') 50 >>> ord('4') 52 >>> ord('a') 97 >>> ord('b') 98 >>> ord('p') 112 #如果需要排序的是一個列表嵌套元組,則需要使用參數key,指定關鍵字 >>> a = [('b',2),('a',1),('c',0)] >>> sorted(a,key=lambda x:x[0]) [('a', 1), ('b', 2), ('c', 0)] >>> sorted(a,key=lambda x:x[1]) [('c', 0), ('a', 1), ('b', 2)] >>> tup1 = ('python','java','c++','bash','php','perl','c#') >>> tup1 ('python', 'java', 'c++', 'bash', 'php', 'perl', 'c#') >>> sorted(tup1,key=str.lower) #忽略大小寫排序 ['bash', 'c#', 'c++', 'java', 'perl', 'php', 'python'] >>> sorted(tup1,key=str.lower,reverse=True) #反向排序 ['python', 'php', 'perl', 'java', 'c++', 'c#', 'bash']
#嵌套字典,按某個鍵值排序 >>>alist = [{'name':'a','age':20},{'name':'b','age':30},{'name':'c','age':25}] >>>sorted(alist,key=lambda x:x['age'],reverse=False) #False為升序,True降序 [{'age': 20, 'name': 'a'}, {'age': 25, 'name': 'c'}, {'age': 30, 'name': 'b'}]
16.ascii()
類似 repr() 函數, 返回一個表示對象的字符串, 但是對於字符串中的非 ASCII 字符則返回通過 repr() 函數使用 \x, \u 或 \U 編碼的字符
>>> ascii('bb') "'bb'" >>> ascii('+') "'+'" >>> ascii('中') "'\\u4e2d'"
17.enumerate()
函數用於將一個可遍歷的數據對象(如列表、元組或字符串)組合為一個索引序列,同時列出數據和數據下標,一般用在 for 循環當中
語法:enumerate(sequence,[start=o])
sequence:一個序列,迭代器或其他支持迭代對象
start:下標起始位置
>>> l1 = ['python','c++','java','php','css'] >>> list(enumerate(l1)) #生成數據和數據下標 [(0, 'python'), (1, 'c++'), (2, 'java'), (3, 'php'), (4, 'css')] >>> list(enumerate(l1,1)) #指定下標從1開始 [(1, 'python'), (2, 'c++'), (3, 'java'), (4, 'php'), (5, 'css')] >>> l1 = ['python','c++','java','php','css'] >>> for i,v in enumerate(l1): ... print(i,v) ... 0 python 1 c++ 2 java 3 php 4 css
18.input()
用來獲取交換輸入,python3默認接受的是字符串
>>> in1 =input('inside:') inside:123 >>> type(in1) #默認接受字符串 <class 'str'> >>> in2 =input('inside:') inside:python >>> type(in2) <class 'str'>
19.oct()
將一個整數轉換成8進制字符串
>>> oct(10) #十進制轉八進制 '0o12' >>> oct(0b1010) #二進制轉八進制 '0o12' >>> oct(0xA) #十六進制轉八進制 '0o12' >>> oct(3.3) #不支持float浮點型轉八進制 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'float' object cannot be interpreted as an integer >>> oct(0.1+1.2j) #不支持complex復數轉八進制 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'complex' object cannot be interpreted as an integer
20.staticmethod()
返回函數的靜態方法
21.bin()
返回一個整數 int 或者長整數 long int 的二進制表示。可以將八進制,十進制,十六進制轉換為二進制,不支持float類型
>>> bin(10) #十進制轉二進制 '0b1010' >>> bin(10.1) #float不支持轉二進制 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'float' object cannot be interpreted as an integer >>> bin(0o10) #八進制轉二進制 '0b1000' >>> bin(0xA) #十六進制轉二進制 '0b1010'
22.eval()
用來執行一個字符串表達式,並返回表達式的值。
>>> eval('123') 123 >>> a = eval('123') #可以將數值字符串轉換為int類型 >>> type(a) <class 'int'> >>> eval('2**8') #將數值字符串當表達式並計算結果返回int類型 256 >>> eval("'a'+'b'") #字符串運算,必須這么寫 'ab' >>> eval("'a'*5") #必須這么寫,5不能加引號否則報錯 'aaaaa' >>> eval("'a'*'5'") Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1, in <module> TypeError: can't multiply sequence by non-int of type 'str'
23.int()
用於將一個字符串數值或數字轉換為整形
>>> int() #不傳入參數結果為0 0 >>> a =int('2') #將字符串轉換成int類型 >>> type(a) <class 'int'> >>> a 2 >>> int(2.6) #將浮點型轉換為整型 2 >>> b =int('12',16) #以字符串的十六進制轉換為十進制 >>> type(b) <class 'int'> >>> b 18 >>> int('0xC',16) #可以這樣寫十六進制 12 >>> int('10',8) #八進制轉十進制 8 >>> int('0o10',8) 8 >>> int('0b1000',2) #二進制轉十進制 8 >>> int('1000',2) #可以省略進制表示法 8
24.open()
用於打開一個文件,創建一個 file 對象,相關的方法才可以調用它進行讀寫
>>> f = open('aa.txt','r+') #以讀寫方式打開一個文件 >>> f.write('hello python\n') #寫入內容到文件中 13 >>> f.flush() #刷新文件內容 >>> f.tell() #查看指針位置 13 >>> f.seek(0) #移動文件指針到起始位置 0 >>> f.tell() #查看指針 0 >>> f.readline() #根據指針位置返回一行文件內容 'hello python\n' file1 = open('aa.txt','a+',1) #以追加寫的模式打開文件,1表示行緩沖,如為0則不緩沖,大於1時表示緩沖區大小,為負數時使用系統默認值。
25.str()
將字節轉換成字符串,bytes() 將字符串轉換為字節
>>> s1=str(11) >>> type(s1) #將對象轉換成字符串 <class 'str'> >>> bytes('中',encoding = 'utf-8') #將字符串轉換bytes字節 b'\xe4\xb8\xad' >>> str(b'\xe4\xb8\xad',encoding = 'utf-8') #將字節轉換為字符串 '中' >>> bytes() #生成空字節對象 b''
26.bool()
判斷給的參數是否為真,則返回True,否則返回False
>>> bool() False >>> bool(0) False >>> bool(1) True >>> bool(2) True >>> bool(False) False >>> bool(True) True >>> bool('') False >>> bool('a') True >>> bool(None) False >>> bool("") False >>> bool([]) False >>> bool(()) False >>> bool({}) False
27.exec()
執行字符串或complie方法編譯過的字符串,沒有返回值
>>> exec("a=1+2+3+4") >>> a 10 >>> exec('''sum = 0 ... for i in range(101): ... sum+=i ... print(sum) ... ''') 5050
28.isinstance()
判斷對象是否是某個類的實例
>>> isinstance('a',str) #判斷a是否是字符類的對象 True >>> isinstance('a',int) False >>> isinstance(11,int) True >>> isinstance({1:'a'},dict) True >>> isinstance({1,2},dict) False >>> isinstance({1,2},set) True >>> isinstance((1,2),(str,int,list)) #判斷對象是否在元祖中的一個類創建返回True,否則返回False False >>> isinstance((1,2),(str,int,list,tuple)) True
29.ord()
ord() 函數是 chr() 函數(對於8位的ASCII字符串)或 unichr() 函數(對於Unicode對象)的配對函數,它以一個字符(長度為1的字符串)作為參數,返回對應的 ASCII 數值,或者 Unicode 數值,如果所給的 Unicode 字符超出了你的 Python 定義范圍,則會引發一個 TypeError 的異常
>>> ord('2') #長度只能為一個字符串 50 >>> ord('a') 97 >>> ord('A') 65 >>> ord('中') #返回對應的unicode值 20013 >>> ord('國') 22269 >>> ord('+') #返回ascii數值 43
30.sum()
對系列進行求和計算,只能是列表或元祖
>>> sum([1,2,3,4]) #求有序列的和,只能是數字類型 10 >>> sum([1,2,3,4],5) #對有序列求和后相加的數字 15
31.bytearray()
返回一個新字節數組。這個數組里的元素是可變的,並且每個元素的值范圍: 0 <= x < 256
>>> bytearray() #沒有參數時,初始化數組0個元素 bytearray(b'') >>> bytearray(12) #為整數時,返回一個長度為源的初始化數組 bytearray(b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00') >>> bytearray('python','utf-8') #為字符串時,按指定編碼轉換為字節序列 bytearray(b'python') >>> bytearray([1,2,3]) #可迭代時,必須為0-255中的整數,字節序列 bytearray(b'\x01\x02\x03')
32.filter()
用於過濾序列,過濾掉不符合條件的元素,返回由符合條件元素組成的迭代器
語法:filter(function,iterable) function:判斷函數,iterable:可迭代對象
>>> def is_odd(x): ... return x % 2 == 1 #創建一個過濾奇數的函數 ... >>> newlist = filter(is_odd,[1,2,3,4,5,6,7,8,9]) #使用filter過濾以is_odd函數為判斷依據的迭代器 >>> print(newlist) <filter object at 0x7f544ab79908> >>> next(newlist) #使用next打印迭代器的下一個值 1 >>> next(newlist) 3 >>> next(newlist) 5 >>> next(newlist) 7 >>> next(newlist) 9
33.issubclass()
用於判斷參數 class 是否是類型參數 classinfo 的子類
class A(object): pass class B(A): pass print(issubclass(B,A)) #判斷B是否是A的派生類,是返回True,否則返回False
34.pow()
返回x的y次方,如果z存在則再對結果取模(pow(x,y)%z)
>>> pow(6,2) #6的2次方 36 >>> pow(6,2,5) #先預算6的2次方,在對結果取5的模 1 >>> pow(8,2) 64 >>> pow(8,2,5) 4 #math模塊的pow()方法對比 >>> import math >>> math.pow(6,2) #math模塊會把參數轉換成float計算 36.0 >>> math.pow(6,2,5) #math模塊中沒有取模方法參數 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: pow expected 2 arguments, got 3
35.super()
調用父類的方法
class A(object): def __init__(self): self.name = 'python' def foo(self): print('class,A') class B(A): super(A) #調用父類的方法和屬性 def foo_b(self): print('class',self.name) #print(issubclass(B,A)) bb = B() bb.foo() bb.foo_b() #output class,A class python
36.float()
用於將整數和字符串轉換成浮點數
>>> float(2) 2.0 >>> float('2') 2.0 >>> float(-23) -23.0
37.iter()
用來生成迭代器
>>> new1 = iter(('a','b','c','e','g')) >>> new1 <tuple_iterator object at 0x7f544ab7b5f8> >>> next(new1) 'a' >>> next(new1) 'b'
38.print()
打印輸出
語法:print(*objects,sep=' ',end='\n',file=sys.stdout)
- objects -- 復數,表示可以一次輸出多個對象。輸出多個對象時,需要用 , 分隔。
- sep -- 用來間隔多個對象,默認值是一個空格。
- end -- 用來設定以什么結尾。默認值是換行符 \n,我們可以換成其他字符串。
- file -- 要寫入的文件對象。
>>> print('hello world') hello world >>> print('hello world',123) #多對象打印 hello world 123 >>> print('hello world',123,sep='++') #多對象打印連接符 hello world++123 >>> print('hello world',123,sep='++',end='\t') #結尾符設置 hello world++123 >>> >>> print('hello world',123,sep='++',end='') hello world++123>>>
39.tuple()
將列表轉換成元組
>>> tuple([1,2,3,4,5]) #列表轉元組 (1, 2, 3, 4, 5) >>> tuple({1,2,3,4,5}) #集合轉元組 (1, 2, 3, 4, 5) >>> tuple({1:'a',2:'b',3:'c'}) #字典轉元組,只獲取自動的key (1, 2, 3)
40.callable()
檢查一個對象是否是可調用的,返回True否則返回False
>>> def func(): ... return 1 + 2 ... >>> func() 3 >>> callable(func) #對象函數可執行返回True True
41.format()
格式化字符串,語法通過{}和:來代替以前的%,不限制參數個數,可以不按順序傳參
In [27]: '{}+{}={}'.format(1,2,3) #格式化按順序應用參數值 Out[27]: '1+2=3' In [28]: '{2}-{1}={0}'.format(1,2,3) #指定順序應用參數值,0代表第一個元素,1代表第二個元素,以此類推,指定元素位置時要么全部指定,要不都不指定,不能只指定一部分 Out[28]: '3-2=1' In [29]: '{0}+{0}={1}'.format(2,3) #指定參數可以重復使用 Out[29]: '2+2=3' In [30]: '{}+{}={}'.format(2,3) #如不指定順序,format參數不夠就會報錯 --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-30-29f40e412920> in <module>() ----> 1 '{}+{}={}'.format(2,3) IndexError: tuple index out of range In [31]: l1 = [2,4,8] In [32]: '{}*{}={}'.format(*l1) #使用列表引用參數值 Out[32]: '2*4=8' In [33]: dct = {'name':'python','age':20} #定義字典 In [35]: 'welcom to {name},age is {age}'.format(name='qi',age=28) #變量引用 Out[35]: 'welcom to qi,age is 28' In [36]: 'welcom to {name},age is {age}'.format(**dct) #使用**引用字典參數必須填寫key值 Out[36]: 'welcom to python,age is 20' 填充與格式化: In [53]: "{0: >20}".format("string") #使用空格填充20寬度右對齊,0代表指定第一個參數值 Out[53]: ' string' In [54]: "{0:&>20}".format("string") Out[54]: '&&&&&&&&&&&&&&string' In [55]: "{0:#>20}".format("string") #使用#號會有個小bug ....: Out[55]: '##############string' In [60]: '{0:+<20}'.format("string") #向左對齊填充+ Out[60]: 'string++++++++++++++' In [61]: '{0:+^20}'.format("string") #劇中對齊填充+ Out[61]: '+++++++string+++++++' 精度與進制: >>> '{0:.3f}'.format(10/3) #小數位進度格式化 '3.333' >>> '{0:b}'.format(8) #格式化二進制 '1000' >>> '{0:o}'.format(9) #格式化八進制 '11' >>> '{0:x}'.format(26) #格式化十六進制 '1a' >>> '{0:,}'.format(123456789) #千分位格式化 '123,456,789' 使用索引: >>> l2 = ['AA',{'bb':'cc'},('d','e')] #列表索引引用 >>> 'outing:{0[0]}'.format(l2) 'outing:AA' >>> 'outing:{0[0]},{0[1]}'.format(l2) #將列表當成一個元素,在其中索引值 "outing:AA,{'bb': 'cc'}"
42.len()
返回對象(字符、列表、元組等)長度或項目個數
>>> len('python') 6 >>> len('123') 3 >>> len([1,2,3,4]) 4 >>> len((1,2,3,4)) 4 >>> len({1:'a',2:'b',3:'c'}) 3 >>> len({1,2,3,4}) 4
43.property()
在新式類中返回屬性值
44.type()
返回對象的類型
>>> type('123') <class 'str'> >>> type(12) <class 'int'> >>> type(12.2) <class 'float'> >>> type([]) <class 'list'> >>> type(()) <class 'tuple'> >>> type({}) <class 'dict'> >>> type({1,2,3}) <class 'set'>
45.chr()
返回一個數字在ASCII編碼中對應的字符,取值范圍256個
>>> chr(1) '\x01' >>> chr(11) '\x0b' >>> chr(255) 'ÿ' >>> chr(256) 'Ā' >>> chr(257) 'ā' >>> chr(0x31) '1' >>> chr(0x3) '\x03' >>> chr(0x11) '\x11'
46.frozenset()
返回一個凍結的集合,凍結后集合不能再添加或刪除任何元素
>>> set1 = frozenset([1,2,3,4]) #列表返回一個不可變集合 >>> set1 frozenset({1, 2, 3, 4}) >>> frozenset((5,6,7)) #元祖返回一個不可變集合 frozenset({5, 6, 7}) >>> a {1: 'a', 2: 'b', 3: 'c'} >>> frozenset(a) #字典返回一個不可變集合 frozenset({1, 2, 3}) >>> frozenset({3,4,5}) #集合返回一個不可變集合 frozenset({3, 4, 5})
47.list()
將字符串或元祖轉換為列表
>>> l1 = list('python') #字符串轉列表 >>> type(l1) <class 'list'> >>> l1 ['p', 'y', 't', 'h', 'o', 'n'] >>> list((1,2,3,4,5)) #元祖轉列表 [1, 2, 3, 4, 5] >>> dic1 = {1:'a',2:'b',3:'c'} >>> list(dic1) #字典轉列表 [1, 2, 3] >>> list({1,2,3,4}) #集合轉列表 [1, 2, 3, 4] >>> list() #返回空列表 []
48.range()
創建一個整數列表
>>> l1 = range(5) >>> l1 range(0, 5) >>> for i in l1: #循環取序列 ... print(i) ... 0 1 2 3 4 >>> for i in range(1,4):print(i) #指定起始和結束位置 ... 1 2 3 >>> for i in range(1,10,3):print(i) #指定起始和結束位置和步長 ... 1 4 7 >>> for i in range(0,-10,-4):print(i) #負數以補償循環 ... 0 -4 -8 >>> for i in range(len('python')):print('python'[i]) #字符串循環打印 ... p y t h o n
49.vars()
返回當前模塊中的所有變量
>>> class runoob: ... a = 1 ... >>> print(vars(runoob)) {'__dict__': <attribute '__dict__' of 'runoob' objects>, '__module__': '__main__', '__doc__': None, '__weakref__': <attribute '__weakref__' of 'runoob' objects>, 'a': 1} >>> aa = runoob() >>> aa <__main__.runoob object at 0x7f98f1b3c0d0> >>> print(vars(aa)) {}
50.classmethod()
返回一個類方法,具體實例請看python3之面向對象類定義
51.getattr()
返回一個對象屬性值,也就是函數內存地址
class test(object): i = 'hello' def show(self): print('output:',self.i) obj1 = test() #實例化對象 ss = getattr(obj1,'show') #返回一個對象的方法內存地址 ss() #執行對象方法 #output output: hello
52.set()
創建一個無序不重復元素集,可進行關系測試,刪除重復數據,還可以計算交集、差集、並集等
>>> s1 = set('pythonpython') >>> s1 = set('pythonpython') #重復的被刪除 >>> s1 {'h', 'n', 'o', 'p', 't', 'y'} >>> type(s1) <class 'set'> >>> s2 = set('pyqi') >>> s2 {'p', 'y', 'i', 'q'} >>> s1 & s2 #交集 {'p', 'y'} >>> s1 | s2 #並集 {'p', 'q', 't', 'i', 'h', 'y', 'n', 'o'} >>> s1 - s2 #差集i {'h', 't', 'n', 'o'}
53.locals()
以字典類型返回當前位置的全部局部變量
>>> def funct(*args): #兩個局部變量 ... a = 22 ... print(locals()) ... >>> funct(33,44) #返回所有局部變量的健值 {'a': 22, 'args': (33, 44)}
54.repr()
將對象轉化為供解釋器讀取的形式
>>> aa = repr([1,2,3]) >>> type(aa) #將對象轉換為字符 <class 'str'> >>> repr({'a':'A','b':'B'}) "{'a': 'A', 'b': 'B'}"
55.zip()
用於將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然后返回由這些元組組成的列表
如果各個迭代器的元素個數不一致,則返回列表長度與最短的對象相同,利用 * 號操作符,可以將元組解壓為列表
>>> aa = (zip([1,2,3],['a','b','c'])) >>> aa <zip object at 0x7f98f1893680> >>> next(aa) (1, 'a') >>> next(aa) (2, 'b') >>> next(aa) (3, 'c') >>> bb = zip([1,2,3],['a','b','c','d'],['A','B','C','D','E']) >>> bb <zip object at 0x7f98f18936c8> >>> next(bb) (1, 'a', 'A') >>> next(bb) (2, 'b', 'B') >>> next(bb) (3, 'c', 'C')
56.compile()
將一個字符串編譯為字節代碼
>>> str = 'for i in range(10):print(i)' >>> c = compile(str,'','exec') >>> c <code object <module> at 0x7f98f1b774b0, file "", line 1> >>> exec(c) 0 1 2 3 4 5 6 7 8 9 >>> str = '3*5+3' >>> a = compile(str,'','eval') >>> eval(a) 18
57.globals()
以字典類型返回當前位置的全部全局變量
>>> a = 'python' >>> print(globals()) #返回一個全局變量的字典,包括導入的變量 {'__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__builtins__': <module 'builtins' (built-in)>, 'a': 'python', '__name__': '__main__', '__doc__': None, '__package__': None, '__spec__': None}
58.map()
將函數調用映射到每個序列的對應元素上並返回一個含有所有返回值的列表
>>> def out(x,y): ... return (x,y) ... >>> l1 =map(out,[1,2,3,4,5],['a','b','c','d','e']) #映射序列,返回函數的值 >>> print(list(l1)) [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')] >>> def foo(x,y): ... return x*y ... >>> print(list(map(foo,[2,3,4],[5,6,7]))) [10, 18, 28]
59.reversed()
返回一個反轉的迭代器
>>> print(list(reversed(range(10)))) #range反轉 [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] >>> print(list(reversed(['a','c','f']))) ['f', 'c', 'a'] >>> print(list(reversed(('java','c++','python')))) ['python', 'c++', 'java'] >>> print(list(reversed('python'))) ['n', 'o', 'h', 't', 'y', 'p']
60.__import__()
用於動態加載類和函數
61.complex()
返回一個復數
>>> complex(1,2) (1+2j) >>> complex('2') (2+0j) >>> complex('2','3') #為字符串時只能指定一位 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: complex() can't take second arg if first is a string >>> complex('2+3j') (2+3j)
62.hasattr()
用於判斷對象是否包含對應的屬性
>>> print(hasattr(list,'append')) True >>> print(hasattr(tuple,'append')) False >>> print(hasattr(tuple,'index')) True >>> print(hasattr(dict,'keys')) True >>> print(hasattr(dict,'values')) True
63.max()
返回給定參數的最大值
>>> max([2,44,55,88]) 88 >>> max((3,48)) 48 >>> max({1:48,2:23}) 2
64.round()
返回浮點數x的四舍五入值
>>> print(round(1.345)) 1 >>> print(round(1.345,3)) #3為小數點后位數 1.345 >>> print(round(1.345,2)) 1.34 >>> print(round(1.345,1)) 1.3 >>> print(round(1.545,1)) 1.5 >>> print(round(1.545,2)) 1.54
65.delattr()
刪除對象的屬性
66.hash()
獲取一個對象(字符串或者數值等)的哈希值
>>> hash('python') -7183818677546017823 >>> hash(1) 1 >>> hash(36) 36 >>> hash([1,2,3]) #列表不能取哈希值 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unhashable type: 'list' >>> hash(str([1,2,3])) -1281906435344341319 >>> hash(str({1:'a'})) -6473938891374685725 >>> hash(str({'1':'1'})) -5747816388481399936
67.memoryview()
返回字節對象的內存地址
>>> a = bytes([1,2,3]) #定義一個字節對象 >>> a b'\x01\x02\x03' >>> memoryview(a) <memory at 0x7f7cd1bbcb88> >>> b = memoryview(a) #返回字節對象的內存地址 >>> b[0] 1 >>> b[1] 2 >>> b[1:4] #切片取的是一個迭代器 <memory at 0x7f7cd1bbcb88> >>> b[1:3].tobytes() b'\x02\x03' >>> for i in b:print(i) #迭代取數值 ... 1 2 3
后續更新實例。。。。
