<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          Python打基礎(chǔ)一定要吃透這68個(gè)內(nèi)置函數(shù)

          共 8254字,需瀏覽 17分鐘

           ·

          2020-07-31 19:57

          點(diǎn)擊上方“測(cè)試開(kāi)發(fā)社區(qū)”,關(guān)注并“星標(biāo)

          接收Python、測(cè)試干貨!

          作者:pypypypy

          來(lái)源:博客園

          內(nèi)置函數(shù)就是Python給你提供的, 拿來(lái)直接用的函數(shù),比如print.,input等。截止到python版本3.6.2 python一共提供了68個(gè)內(nèi)置函數(shù),具體如下?

          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()??????lter()???????issubclass()???pow()?????????super()?
          bytes()??????????oat()????????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()

          本文將這68個(gè)內(nèi)置函數(shù)綜合整理為12大類(lèi),正在學(xué)習(xí)Python基礎(chǔ)的讀者一定不要錯(cuò)過(guò),建議收藏學(xué)習(xí)!

          和數(shù)字相關(guān)

          1. 數(shù)據(jù)類(lèi)型


          • bool : 布爾型(True,False)

          • int : 整型(整數(shù))

          • float : 浮點(diǎn)型(小數(shù))

          • complex : 復(fù)數(shù)

          2. 進(jìn)制轉(zhuǎn)換


          • bin() 將給的參數(shù)轉(zhuǎn)換成二進(jìn)制

          • otc() 將給的參數(shù)轉(zhuǎn)換成八進(jìn)制

          • hex() 將給的參數(shù)轉(zhuǎn)換成十六進(jìn)制

          print(bin(10))  # 二進(jìn)制:0b1010print(hex(10))  # 十六進(jìn)制:0xaprint(oct(10))  # 八進(jìn)制:0o12

          3. 數(shù)學(xué)運(yùn)算


          • abs() 返回絕對(duì)值

          • divmode() 返回商和余數(shù)

          • round() 四舍五入

          • pow(a, b) 求a的b次冪, 如果有三個(gè)參數(shù). 則求完次冪后對(duì)第三個(gè)數(shù)取余

          • sum() 求和

          • min() 求最小值

          • max() 求最大值


          print(abs(-2))  # 絕對(duì)值:2print(divmod(20,3)) # 求商和余數(shù):(6,2)print(round(4.50))   # 五舍六入:4print(round(4.51))   #5print(pow(10,2,3))  # 如果給了第三個(gè)參數(shù). 表示最后取余:1print(sum([1,2,3,4,5,6,7,8,9,10]))  # 求和:55print(min(5,3,9,12,7,2))  #求最小值:2print(max(7,3,15,9,4,13))  #求最大值:15

          和數(shù)據(jù)結(jié)構(gòu)相關(guān)

          1. 序列


          (1)列表和元組


          • list() 將一個(gè)可迭代對(duì)象轉(zhuǎn)換成列表

          • tuple() 將一個(gè)可迭代對(duì)象轉(zhuǎn)換成元組


          print(list((1,2,3,4,5,6)))  #[1, 2, 3, 4, 5, 6]print(tuple([1,2,3,4,5,6]))  #(1, 2, 3, 4, 5, 6)


          (2)相關(guān)內(nèi)置函數(shù)


          • reversed() 將一個(gè)序列翻轉(zhuǎn), 返回翻轉(zhuǎn)序列的迭代器

          • slice() 列表的切片


          lst = "你好啊"it = reversed(lst)   # 不會(huì)改變?cè)斜? 返回一個(gè)迭代器, 設(shè)計(jì)上的一個(gè)規(guī)則print(list(it))  #['啊', '好', '你']lst = [1, 2, 3, 4, 5, 6, 7]print(lst[1:3:1])  #[2,3]s = slice(1, 3, 1)  #  切片用的print(lst[s])  #[2,3]

          (3)字符串


          • str() 將數(shù)據(jù)轉(zhuǎn)化成字符串


          print(str(123)+'456')  #123456  format()     與具體數(shù)據(jù)相關(guān), 用于計(jì)算各種小數(shù), 精算等.

          s = "hello world!"print(format(s, "^20"))  #劇中print(format(s, "<20"))  #左對(duì)齊print(format(s, ">20"))  #右對(duì)齊#     hello world!    # hello world!        #         hello world!print(format(3, 'b' ))    # 二進(jìn)制:11print(format(97, 'c' ))   # 轉(zhuǎn)換成unicode字符:aprint(format(11, 'd' ))   # ?進(jìn)制:11print(format(11, 'o' ))   # 八進(jìn)制:13 print(format(11, 'x' ))   # 十六進(jìn)制(?寫(xiě)字母):bprint(format(11, 'X' ))   # 十六進(jìn)制(大寫(xiě)字母):Bprint(format(11, 'n' ))   # 和d?樣:11print(format(11))         # 和d?樣:11
          print(format(123456789, 'e' )) # 科學(xué)計(jì)數(shù)法. 默認(rèn)保留6位小數(shù):1.234568e+08print(format(123456789, '0.2e' )) # 科學(xué)計(jì)數(shù)法. 保留2位小數(shù)(小寫(xiě)):1.23e+08print(format(123456789, '0.2E' )) # 科學(xué)計(jì)數(shù)法. 保留2位小數(shù)(大寫(xiě)):1.23E+08print(format(1.23456789, 'f' )) # 小數(shù)點(diǎn)計(jì)數(shù)法. 保留6位小數(shù):1.234568print(format(1.23456789, '0.2f' )) # 小數(shù)點(diǎn)計(jì)數(shù)法. 保留2位小數(shù):1.23print(format(1.23456789, '0.10f')) # 小數(shù)點(diǎn)計(jì)數(shù)法. 保留10位小數(shù):1.2345678900print(format(1.23456789e+3, 'F')) # 小數(shù)點(diǎn)計(jì)數(shù)法. 很大的時(shí)候輸出INF:1234.567890

          • bytes() 把字符串轉(zhuǎn)化成bytes類(lèi)型


          bs = bytes("今天吃飯了嗎", encoding="utf-8")print(bs)  #b'\xe4\xbb\x8a\xe5\xa4\xa9\xe5\x90\x83\xe9\xa5\xad\xe4\xba\x86\xe5\x90\x97'   bytearray()    返回一個(gè)新字節(jié)數(shù)組. 這個(gè)數(shù)字的元素是可變的, 并且每個(gè)元素的值得范圍是[0,256)
          ret = bytearray("alex" ,encoding ='utf-8')print(ret[0]) #97print(ret) #bytearray(b'alex')ret[0] = 65 #把65的位置A賦值給ret[0]print(str(ret)) #bytearray(b'Alex')

          • ord() 輸入字符找?guī)ё址幋a的位置

          • chr() 輸入位置數(shù)字找出對(duì)應(yīng)的字符

          • ascii() 是ascii碼中的返回該值 不是就返回u


          print(ord('a'))  # 字母a在編碼表中的碼位:97print(ord('中'))  # '中'字在編碼表中的位置:20013
          print(chr(65)) # 已知碼位,求字符是什么:Aprint(chr(19999)) #丟
          for i in range(65536): #打印出0到65535的字符 print(chr(i), end=" ")
          print(ascii("@")) #'@'

          • repr() 返回一個(gè)對(duì)象的string形式


          s = "今天\n吃了%s頓\t飯" % 3print(s)#今天# 吃了3頓    飯print(repr(s))   # 原樣輸出,過(guò)濾掉轉(zhuǎn)義字符 \n \t \r 不管百分號(hào)%#'今天\n吃了3頓\t飯'

          2. 數(shù)據(jù)集合


          • 字典:dict 創(chuàng)建一個(gè)字典

          • 集合:set 創(chuàng)建一個(gè)集合


          frozenset() 創(chuàng)建一個(gè)凍結(jié)的集合,凍結(jié)的集合不能進(jìn)行添加和刪除操作。

          3. 相關(guān)內(nèi)置函數(shù)


          • len() 返回一個(gè)對(duì)象中的元素的個(gè)數(shù)

          • sorted() 對(duì)可迭代對(duì)象進(jìn)行排序操作 (lamda)


          語(yǔ)法:sorted(Iterable, key=函數(shù)(排序規(guī)則), reverse=False)


          • Iterable: 可迭代對(duì)象

          • key: 排序規(guī)則(排序函數(shù)), 在sorted內(nèi)部會(huì)將可迭代對(duì)象中的每一個(gè)元素傳遞給這個(gè)函數(shù)的參數(shù). 根據(jù)函數(shù)運(yùn)算的結(jié)果進(jìn)行排序

          • reverse: 是否是倒敘. True: 倒敘, False: 正序


          lst = [5,7,6,12,1,13,9,18,5]lst.sort()  # sort是list里面的一個(gè)方法print(lst)  #[1, 5, 5, 6, 7, 9, 12, 13, 18]
          ll = sorted(lst) # 內(nèi)置函數(shù). 返回給你一個(gè)新列表 新列表是被排序的print(ll) #[1, 5, 5, 6, 7, 9, 12, 13, 18]
          l2 = sorted(lst,reverse=True) #倒序print(l2) #[18, 13, 12, 9, 7, 6, 5, 5, 1]

          #根據(jù)字符串長(zhǎng)度給列表排序lst = ['one', 'two', 'three', 'four', 'five', 'six']def f(s):    return len(s)l1 = sorted(lst, key=f, )print(l1)  #['one', 'two', 'six', 'four', 'five', 'three']

          • enumerate() 獲取集合的枚舉對(duì)象


          lst = ['one','two','three','four','five']for index, el in enumerate(lst,1):    # 把索引和元素一起獲取,索引默認(rèn)從0開(kāi)始. 可以更改    print(index)    print(el)# 1# one# 2# two# 3# three# 4# four# 5# five

          • all() 可迭代對(duì)象中全部是True, 結(jié)果才是True

          • any() 可迭代對(duì)象中有一個(gè)是True, 結(jié)果就是True


          print(all([1,'hello',True,9]))  #Trueprint(any([0,0,0,False,1,'good']))  #True

          • zip() 函數(shù)用于將可迭代的對(duì)象作為參數(shù), 將對(duì)象中對(duì)應(yīng)的元素打包成一個(gè)元組, 然后返回由這些元組組成的列表. 如果各個(gè)迭代器的元素個(gè)數(shù)不一致, 則返回列表長(zhǎng)度與最短的對(duì)象相同


          lst1 = [1, 2, 3, 4, 5, 6]lst2 = ['醉鄉(xiāng)民謠', '驢得水', '放牛班的春天', '美麗人生', '辯護(hù)人', '被嫌棄的松子的一生']lst3 = ['美國(guó)', '中國(guó)', '法國(guó)', '意大利', '韓國(guó)', '日本']print(zip(lst1, lst1, lst3))  #for el in zip(lst1, lst2, lst3):    print(el)# (1, '醉鄉(xiāng)民謠', '美國(guó)')# (2, '驢得水', '中國(guó)')# (3, '放牛班的春天', '法國(guó)')# (4, '美麗人生', '意大利')# (5, '辯護(hù)人', '韓國(guó)')# (6, '被嫌棄的松子的一生', '日本')

          • fiter() 過(guò)濾 (lamda)


          語(yǔ)法:fiter(function. Iterable)


          function: 用來(lái)篩選的函數(shù). 在?lter中會(huì)自動(dòng)的把iterable中的元素傳遞給function. 然后根據(jù)function返回的True或者False來(lái)判斷是否保留留此項(xiàng)數(shù)據(jù) , Iterable: 可迭代對(duì)象


          def func(i):    # 判斷奇數(shù)    return i % 2 == 1    lst = [1,2,3,4,5,6,7,8,9]l1 = filter(func, lst)  #l1是迭代器print(l1)  #<filter object at 0x000001CE3CA98AC8>print(list(l1))  #[1, 3, 5, 7, 9]


          • map() 會(huì)根據(jù)提供的函數(shù)對(duì)指定序列列做映射(lamda)


          語(yǔ)法 : map(function, iterable)?


          可以對(duì)可迭代對(duì)象中的每一個(gè)元素進(jìn)行映射. 分別去執(zhí)行 function


          def f(i):    return ilst = [1,2,3,4,5,6,7,]it = map(f, lst) # 把可迭代對(duì)象中的每一個(gè)元素傳遞給前面的函數(shù)進(jìn)行處理. 處理的結(jié)果會(huì)返回成迭代器print(list(it))  #[1, 2, 3, 4, 5, 6, 7]

          和作用域相關(guān)


          • locals() 返回當(dāng)前作用域中的名字

          • globals() 返回全局作用域中的名字


          def func():    a = 10    print(locals())  # 當(dāng)前作用域中的內(nèi)容    print(globals())  # 全局作用域中的內(nèi)容    print("今天內(nèi)容很多")func()# {'a': 10}# {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': # <_frozen_importlib_external.SourceFileLoader object at 0x0000026F8D566080>, # '__spec__': None, '__annotations__': {}, '__builtins__': 'builtins' # (built-in)>, '__file__': 'D:/pycharm/練習(xí)/week03/new14.py', '__cached__': None,#  'func': <function func at 0x0000026F8D6B97B8>}#?今天內(nèi)容很多

          和迭代器生成器相關(guān)


          • range() 生成數(shù)據(jù)

          • next() 迭代器向下執(zhí)行一次, 內(nèi)部實(shí)際使?用了__ next__()?方法返回迭代器的下一個(gè)項(xiàng)目

          • iter() 獲取迭代器, 內(nèi)部實(shí)際使用的是__ iter__()?方法來(lái)獲取迭代器


          for i in range(15,-1,-5):    print(i)# 15# 10# 5# 0lst = [1,2,3,4,5]it = iter(lst)  #  __iter__()獲得迭代器print(it.__next__())  #1print(next(it)) #2  __next__()  print(next(it))  #3print(next(it))  #4

          字符串類(lèi)型代碼的執(zhí)行


          • eval() 執(zhí)行字符串類(lèi)型的代碼. 并返回最終結(jié)果

          • exec() 執(zhí)行字符串類(lèi)型的代碼

          • compile() 將字符串類(lèi)型的代碼編碼. 代碼對(duì)象能夠通過(guò)exec語(yǔ)句來(lái)執(zhí)行或者eval()進(jìn)行求值


          s1 = input("請(qǐng)輸入a+b:")  #輸入:8+9print(eval(s1))  # 17 可以動(dòng)態(tài)的執(zhí)行代碼. 代碼必須有返回值s2 = "for i in range(5): print(i)"a = exec(s2) # exec 執(zhí)行代碼不返回任何內(nèi)容
          # 0# 1# 2# 3# 4print(a) #None
          # 動(dòng)態(tài)執(zhí)行代碼exec("""def func(): print(" 我是周杰倫")""" )func() #我是周杰倫

          code1 = "for i in range(3): print(i)"com = compile(code1, "", mode="exec")   # compile并不會(huì)執(zhí)行你的代碼.只是編譯exec(com)???#?執(zhí)行編譯的結(jié)果# 0# 1# 2
          code2 = "5+6+7"com2 = compile(code2, "", mode="eval")print(eval(com2)) # 18
          code3 = "name = input('請(qǐng)輸入你的名字:')" #輸入:hellocom3 = compile(code3, "", mode="single")exec(com3)print(name) #hello

          輸入輸出


          • print() : 打印輸出

          • input() : 獲取用戶(hù)輸出的內(nèi)容


          print("hello", "world", sep="*", end="@") # sep:打印出的內(nèi)容用什么連接,end:以什么為結(jié)尾#hello*world@

          內(nèi)存相關(guān)


          hash() : 獲取到對(duì)象的哈希值(int, str, bool, tuple). hash算法:(1) 目的是唯一性 (2) dict 查找效率非常高, hash表.用空間換的時(shí)間 比較耗費(fèi)內(nèi)存


          s = 'alex'print(hash(s))  #-168324845050430382

          lst = [1, 2, 3, 4, 5]print(hash(lst)) #報(bào)錯(cuò),列表是不可哈希的  id() : 獲取到對(duì)象的內(nèi)存地址

          s = 'alex'print(id(s)) #2278345368944

          文件操作相關(guān)


          • open() : 用于打開(kāi)一個(gè)文件, 創(chuàng)建一個(gè)文件句柄


          f = open('file',mode='r',encoding='utf-8')f.read()f.close()

          模塊相關(guān)


          • __ import__() : 用于動(dòng)態(tài)加載類(lèi)和函數(shù)


          # 讓用戶(hù)輸入一個(gè)要導(dǎo)入的模塊import osname?=?input("請(qǐng)輸入你要導(dǎo)入的模塊:")__import__(name)????#?可以動(dòng)態(tài)導(dǎo)入模塊

          幫? 助


          • help() : 函數(shù)用于查看函數(shù)或模塊用途的詳細(xì)說(shuō)明


          print(help(str))  #查看字符串的用途

          調(diào)用相關(guān)


          • callable() : 用于檢查一個(gè)對(duì)象是否是可調(diào)用的. 如果返回True, object有可能調(diào)用失敗, 但如果返回False. 那調(diào)用絕對(duì)不會(huì)成功


          a = 10print(callable(a))??#False??變量a不能被調(diào)用#def?f():????print("hello")????print(callable(f))???#?True?函數(shù)是可以被調(diào)用的

          查看內(nèi)置屬性


          • dir() : 查看對(duì)象的內(nèi)置屬性, 訪問(wèn)的是對(duì)象中的__dir__()方法


          print(dir(tuple))  #查看元組的方法




          點(diǎn)個(gè)“在看”支持一下?
          瀏覽 18
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  国产美女极度色诱视频WWW | 蜜臀久久99精品久久久久老师 | 久久偷拍熟女91 | 欧美亲子乱婬性 | www亚洲天堂 |