Python3.6.x中內置函數總結
# -*- coding:utf-8 -*-"""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()"""from collections import Iterator,Iterable# abs(x)# 求絕對值print(abs(-1),abs(1))# all(iterable)# 如果iterable的所有元素都為真,則返回True(iterable為空,返回True)print(all([1,'a',[2]])) # Trueprint(all([0,'a',[]])) # Falseprint(all(''))     # True# any(iterable)# 只要iterable中有一個元素為真,則返回True(iterable為空,返回False)print(any([1,[],'']))    # Trueprint(any([0,0.0,'',[],{},set()]))  # Falseprint(any([]))       # False# ascii(s)# 只在Python3中支持,用于在不支持Unicode的平臺查看Unicode字符串# 就像repr()那樣,創建對象的可打印形式,但在結果中只是用ascii字符,非ascii字符都轉換為合適的轉義序列。print(ascii('hello你好'))# 'hello/u4f60/u597d'# repr(obj)# 將其它類型數據轉換為字符串,支持大部分內置數據類型print(repr(123))      # 123print(repr('hello 你好'))  # 'hello 你好'print(repr([1,2,3]))    # [1, 2, 3]print(repr({'a':1}))    # {'a': 1}print(repr(object()))    # <object object at 0x7f4e9de470a0># str(value='', encoding=None, errors='strict')# 轉換為字符串print(str())    # ''print(str(666))   # 666print(str(6.66))  # 6.66print(str(b'666')) # b'666'# bin(x)# 返回一個字符串,其中包含整數x的二進制形式 0b1010print(bin(0),bin(1),bin(10))# 0b0 0b1 0b1010# class bool([x])# 是class,返回True或Falseprint(bool(),bool(0),bool(1),bool(''),bool('abc'),bool([]),bool([1]),bool(False),bool(True))# False False True False True False True False True# class bytearray(source=None, encoding=None, errors='strict')# 返回一個字節數組,字符范圍[0,255]print(bytearray("hello 你好","utf-8"))# bytearray(b'hello /xe4/xbd/xa0/xe5/xa5/xbd')# bytes(value=b'', encoding=None, errors='strict')# 返回字節類型,字符范圍[0,255]print(bytes("hello 你好","utf-8"))# b'hello /xe4/xbd/xa0/xe5/xa5/xbd'# callable(o)# 返回True或者False,判斷一個給定對象 o 是否是可調用對象print(callable(1),callable(''),callable(str))# False False True# chr(x)# 返回Unicode編碼表中整數x對應的字符print(chr(65),chr(20001))# A 両# ord()# 返回單個字符在Unicode碼表中對應的整數編碼print(ord('A'),ord('李'),ord('永'),ord('平')) # 65 26446 27704 24179# @classmethod()# 將一個普通函數轉換為類方法,等價于@classmethond裝飾器class A():  def func01(*args):    print('classmethod()',*args)  classmethod(func01)  @classmethod  def func02(clz,*args):    print('@classmethond',*args)A.func01()A.func02()# 輸出# classmethod()# @classmethond# @staticmethod# 將一個普通函數轉換為靜態方法class A():  def func01(*args):    print('staticmethod()',*args)  staticmethod(func01)  @staticmethod  def func02(*args):    print('@staticmethod',*args)A.func01()A.func02()# 輸出# staticmethod()# @staticmethod# compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)# 將字符串格式的源代碼,編譯為可以被exec()或eval()函數執行的代碼code對象# source:一個Python模塊或多個代碼塊,或者是單一代碼塊,或者是一個表達式# filename:運行時錯誤消息提示# mode:與source對應,模塊或多個代碼塊--"exec",單一代碼塊--"single",表達式--"eval"statements="""print('-'*50)num=3while num:  print("hello")  num-=1print('-'*50)"""filename="run-time error"codes=compile(source=statements,filename=filename,mode="exec")print(type(codes))# eval(codes)exec(codes)# 輸出# <class 'code'># --------------------------------------------------# hello# hello# hello# --------------------------------------------------# eval(expression, globals=None, locals=None)# 運行Python表達式字符串或者是經過compile()編譯后生成的code對象# obj可以是字符串對象或者已經由compile編譯過的代碼對象,# globals和locals是可選的,分別代表了全局和局部名稱空間中的對象,其中globals必須是字典,而locals是任意的映射對象print(eval("2**3"))   # 8print(eval("type({'key':'value'})"))  # <class 'dict'># exec(object[, globals[, locals]])# 運行Python代碼字符串或者是經過compile()編譯后生成的code對象statements="""num=1if num<3:  print("1<3")"""exec(statements)  # 1<3exec('print("exec")')  # exec# class complex(real, imag=None)# 返回復數c=complex(1,2)print(c,c.real,c.imag)c=complex('1+2j')# c=complex('1 +2j')  # 報錯ValueError,字符串中不能包含空格# c=complex('1+2i')  # 報錯ValueError,復數虛部必須使用英文字母 j 表示print(c,c.real,c.imag)# 輸出# (1+2j) 1.0 2.0# (1+2j) 1.0 2.0# delattr(obj,attr)# 等價于 del obj.attr# 刪除對象obj的attr屬性class A:  attr_01=1  attr_02=2print(A.attr_01)delattr(A,'attr_01')# print(A.attr_01)  # AttributeError: type object 'A' has no attribute 'attr_01'print(A.attr_02)del A.attr_02# print(A.attr_02)  # AttributeError: type object 'A' has no attribute 'attr_02'# class dict(**kwarg)# class dict(mapping, **kwarg)# class dict(iterable, **kwarg)# 返回一個字典對象print(dict())  # {}print(dict(a=2,b=1))  # {'b': 1, 'a': 2}print(dict([('a',1),('b',2),('c',3)])) # {'a': 1, 'b': 2, 'c': 3}print(dict({'a':'A','b':'B'})) # {'a': 'A', 'b': 'B'}# dir(obj)# 參數為空,返回當前作用域中的屬性和方法列表# 參數不為空,返回參數對象obj的作用域中的屬性和方法列表# 參數不為空,且該參數對象所屬類中重載了 __dir__(self) 運算符,則返回 __dir__(self)的返回值print(dir())print(dir(int))print(dir(dict))class B():  def __dir__(self):    return ['哼','哈']  def func(self):    passb=B()print(dir(b))  # ['哈', '哼']# divmod(a,b)# 等價于 (a//b,a%b)# 返回長除法的商與余數組成的元組print(divmod(10,3),(10//3,10%3))print(divmod(10,3.0),(10//3.0,10%3.0))print(divmod(10.0,3),(10.0//3,10.0%3))# (3, 1) (3, 1)# (3.0, 1.0) (3.0, 1.0)# (3.0, 1.0) (3.0, 1.0)# enumerate(i,start=0)# 根據給定iterable,返回枚舉類型對象,是iterator類型print(list(enumerate('abc',start=1)))for item in enumerate('123',start=0):  print(item)# 輸出# [(1, 'a'), (2, 'b'), (3, 'c')]# (0, 'a')# (1, 'b')# (2, 'c')# filter(function, iterable)# 過濾序列中的值# filter函數將序列iterable中的每一個元素傳入函數function中,如果返回值為真,則添加到結果集中;否則,過濾掉# 如果function為None,則將iterable中值為True的元素添加到結果集中data=[-1,0,1,2,3,False]res=filter(lambda x:x>=0,data)print(res)   # <filter object at 0x7f97fe23f7b8>print(list(res))  # [0, 1, 2, 3, False]res=filter(None,data)print(list(res))  # [-1, 1, 2, 3]# class float([x])# 生成浮點數,x為數字或者字符串# inf:無窮print(float(),float(1),float('1'),float('+1.23'),float('+1E6'),float('-Infinity'),float('  -12345/n'))# 0.0 1.0 1.0 1.23 1000000.0 -inf -12345.0# format(value, [format_spec])# 格式化顯示value的值,類型為str# 如果format_spec為空,則等效于str(value)print(format(123)) # 123print(format(True)) # Trueprint(format({'a':1,'b':2}))  # {'a':1,'b':2}print(format(123,'b')) # 格式化為2進制 1111011print(format(123,'o')) # 格式化為8進制 173print(format(123,'d')) # 格式化為10進制 123print(format(123,'x')) # 格式化為16進制,使用小寫字母顯示 7bprint(format(123,'X')) # 格式化為16進制,使用大寫在木顯示 7Bprint(format(123456789.123456789,'e'))   # 科學計數法,默認保留6位小數 1.234568e+08print(format(123456789.123456789,'0.2e'))  # 科學計數法,保留2位小數 1.23e+08print(format(123456789.123456789,'E'))   # 科學計數法,1.234568E+08print(format(123456789.123456789,'0.2E'))  # 科學計數法,1.23E+08print(format(123456789.123456789,'f'))   # 小數點計數法,默認保留6位小數,123456789.123457print(format(123456789.123456789,'0.2f'))  # 小數點計數法,保留2位小數,123456789.12print(format(1.0e+1000,'F'),format(-1.0e+1000,'F')) # 小數點計數法,無窮大轉換為字母 INF,-INF# class set([iterable])# 獲取一個set實例對象,可變,元素不重復print(set())   # set()print(set('123')) # {'2', '3', '1'}# class frozenset([iterable])# 返回一個frozenset實例對象,不可變,元素不重復print(frozenset())   # frozenset()print(frozenset('123')) # frozenset({'2', '3', '1'})# getattr(object, name[, default])# 返回object的name屬性值,name必須是str類型# 如果不存在name屬性,設置了default返回default值,否則,拋出異常AttributeErrorclass A(object):  attr_01='value_01'print(getattr(A,'attr_01'))print(getattr(A,'attr_02','value_02'))# print(getattr(A,'attr_03')) # AttributeError: type object 'A' has no attribute 'attr_03'# hasattr(object, name)# 判斷object是否擁有屬性name,返回True或Falseprint(hasattr(A,'attr_01')) # Trueprint(hasattr(A,'attr_02')) # False# setattr(object, name, value)# 給object設置屬性name,值為valuesetattr(A,'attr_02','value_02')print(hasattr(A,'attr_02')) # True# globals()# 返回屬于全局作用域的屬性或者方法的字典表print(globals())# locals()# 返回屬于本地作用域的屬性和方法的字典表print(locals())def function():  a,b=1,2  print(locals())   # {'b': 2, 'a': 1}function()# vars(object)# 返回任意對象的__dict__屬性,前提是存在該屬性print(vars(int))# hash(object)# 返回object的哈希值,大小相等的數字,哈希值一定相同print(hash(1),hash(1.0))print(hash(A),hash(A()))print(hash(int),hash(hash))# help([object])# 調用內置的幫助系統# object可以為空,module, function, class, method, keyword, or documentation topi# help()# import re# help(re)# help(hash)# help('class')# class int(x=0)# class int(x, base=10)# 將給定數據x從base進制轉換為10進制int# x為數字或可轉換為數字的字符串,base為數字x本來的進制print(int(255)) # 255print(int('255'))  # 255print(int('255',base=10))  # 255print(int('255',base=8))  # 173# oct(x)# 將10進制數x轉換為8進制數print(oct(255)) # 0o377# hex(x)# 將一個int類型的數字轉換為16進制print(hex(255),hex(0)) # 0xff 0x0# id()# 返回代表object身份的一個int數字,可以認為C語言中"對象的內存地址"print(id(0))print(id(id))# input([prompt])# 接收用戶的輸入并返回字符串# value=input('--->')# print(value)# print(*objects, sep=' ', end='/n', file=sys.stdout, flush=False)# *args:任意多個字符串# sep:字符串之間的分割符,默認為空格# end:結束符號,默認為換行 /nprint('a','b','c',sep='$',end='/n/n')# isinstance(object, classinfo)# 判斷object是否是classinfo的一個實例class A():passprint(isinstance(1,int))  # Trueprint(isinstance(A(),A))  # True# issubclass(class, classinfo)# 判斷class是否是classinfo的一個子類class A():passclass B(A):passprint(issubclass(B,A)) # True# iter(object[, sentinel])# 將一個可迭代對象轉換為迭代器Iteratori=iter('abc')print(type(i))# next(iterator[, default])# 返回迭代器的下一個元素# 如果沒有下一個,返回default參數,如果沒有default,拋出StopIteration異常print(next(i),next(i),next(i))# print(next(i)) # StopIterationprint(next(i,'沒有更多元素了'))# len(iterable)# 返回iterable的元素個數print(len('abc'))  # 3print(len([1,2,3])) # 3print(len((1,2,3))) # 3print(len({'a':1})) # 1print(len({1,2,3})) # 3# class list([iterable])# 實例化一個list對象print(list())print(list('abcd'))print(list(range(5)))# map(function, iterable, ...)# 在序列中映射函數:map函數會對一個序列對象中的每一個元素應用被傳入的函數,并返回一個包含所有函數調用結果的映射集合# res=map(lambda x:x,[1,2,3])res=map(lambda x,y:x+y,[1,2,3],[4,5,6])print(type(res))print(list(res))# max()# 返回給定序列中的最大值print(max(1,2))   # 2print(max([1,2]))  # 2print(max({'a':2,'b':1})) # bprint(max({'a','b'}))   # b# min()# 返回給定序列中的最小值print(min(1,2))   # 1print(min([1,2]))  # 1print(min({'a':2,'b':1})) # aprint(min({'a','b'}))   # a# memoryview(object)# 什么鬼?內存視圖?C中的指針?view=memoryview(b'abcd')print(view[0]) # 97# class object# 返回一個objectprint(object) #<class 'object'>print(object()) # <object object at 0x7fc4731ef0c0># open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)# 打開一個文件對象# pow(x,y,[z])# 2個參數時,等效于x**y# 3個參數時,等效于x**y%zprint(pow(10,3))  # 1000print(pow(10,3,3)) # 1# class property(fget=None, fset=None, fdel=None, doc=None)# 不懂?# range([start,]stop[,sep])# 生成數字列表r=range(5)print(type(r),isinstance(r,Iterator))  # <class 'range'> Falsefor i in range(1,10,2):  print(i,end=' ')    # 1 3 5 7 9print('/n')# reversed(seq)# 翻轉序列seq,返回Iteratori=reversed(['a','b','c'])print(i)print(next(i),next(i),next(i),next(i,'沒有了'))# round(number[, ndigits])# 四舍五入# ndigits為保留小數點位數,默認為0print(round(16),round(16.18),round(8.88),round(-8.88))     # 16 16 9 -9print(round(16,1),round(16.18,1),round(8.88,1),round(-8.88,1)) # 16 16.2 8.9 -8.9# class slice(stop)¶# class slice(start, stop[, step])# 返回一個切片slice對象,表示步距,可用于切片操作,實際上對可迭代對象的切片操作就是調用了slice方法print(slice(5))   # slice(None, 5, None)print(slice(1,5))  # slice(1, 5, None)print(slice(1,5,2)) # slice(1, 5, 2)seq='abcdefghj'print(seq[slice(5)])  # abcdeprint(seq[slice(1,5,2)])# bd# sorted(iterable, *, key=None, reverse=False)# 對可迭代對象進行排序# key為函數,依次作用于每個元素# reverse為是否倒序排序print(sorted('872Aadbc',key=None,reverse=True))# ['d', 'c', 'b', 'a', 'A', '8', '7', '2']print(sorted('872Aadbc',key=lambda x :str.lower(x),reverse=True))# ['d', 'c', 'b', 'A', 'a', '8', '7', '2']# sum(iterable[, start])# 求和:iterable中各元素之和,加上第二個參數start的值# 第二個參數start默認為0print(sum([1,2,3]))print(sum([1,2,3],10))# super([type[, object-or-type]])# 調用父類中的方法class A(object):  def methond(self):    print('----A----')class B(A):  def methond(self):    super(B,self).methond()    # 等價于    # super().methond()    print('----B----')B.methond(B())# tuple([iterable])# 返回一個元祖對象,不可變的listprint(tuple(['L','O','V','E','E']))# type(obj)# 返回obj的數據類型print(type(0))print(type(''))print(type([]))print(type((0,)))print(type({}))# zip()# 創建一個迭代器,結果為倆個Iterable中各元素從開始位置開始的映射關系# 如果2個Iterable中的元素個數不同,則舍棄比較多的元素ziped=zip('abcd','1234')print(isinstance(ziped,Iterator))  # Trueprint(list(ziped)) # [('a', 'A'), ('b', 'B'), ('c', 'C'), ('d', 'D')]ziped=zip('abc','1234')print(list(ziped))   # [('a', '1'), ('b', '2'), ('c', '3')]ziped=zip('abcd','123')print(list(ziped))   # [('a', '1'), ('b', '2'), ('c', '3')]print(list(zip('abc'))) # [('a',), ('b',), ('c',)]print(list(zip('abc',''))) # []# __import__(name, globals=None, locals=None, fromlist=(), level=0)# 不常用的高級函數# import importlib# importlib.import_module('module_name')            
新聞熱點
疑難解答