自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Python函數(shù)合集:足足68個內(nèi)置函數(shù)請收好!

開發(fā) 后端
內(nèi)置函數(shù)就是python給你提供的, 拿來直接用的函數(shù),比如print.,input等。截止到python版本3.6.2 python一共提供了68個內(nèi)置函數(shù)。

[[327647]]

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

  1. #68個內(nèi)置函數(shù)  
  2. # abs()           dict()        help()         min()         setattr()  
  3. # all()           dir()         hex()          next()        slice()   
  4. # any()           divmod()      id()           object()      sorted()   
  5. # ascii()         enumerate()   input()        oct()         staticmethod()   
  6. # bin()           eval()        int()          open()        str()   
  7. # bool()          exec()        isinstance()   ord()         sum()   
  8. # bytearray()     filter()       issubclass()   pow()         super()   
  9. # bytes()         float()        iter()         print()       tuple()   
  10. # callable()      format()      len()          property()    type()   
  11. # chr()           frozenset()   list()         range()       vars()   
  12. # classmethod()   getattr()     locals()       repr()        zip()   
  13. # compile()       globals()     map()          reversed()    __import__()   
  14. # complex()       hasattr()     max()          round()   
  15. # delattr()       hash()        memoryview()   set() 

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

1. 數(shù)據(jù)類型

  •  bool : 布爾型(True,False)
  •  int : 整型(整數(shù))
  •  float : 浮點型(小數(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)制 
  1. print(bin(10))  # 二進(jìn)制:0b1010  
  2. print(hex(10))  # 十六進(jìn)制:0xa  
  3. print(oct(10))  # 八進(jìn)制:0o12 

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

  •  abs() 返回絕對值
  •  divmode() 返回商和余數(shù)
  •  round() 四舍五入
  •  pow(a, b) 求a的b次冪, 如果有三個參數(shù). 則求完次冪后對第三個數(shù)取余
  •  sum() 求和
  •  min() 求最小值
  •  max() 求最大值 
  1. print(abs(-2))  # 絕對值:2  
  2. print(divmod(20,3)) # 求商和余數(shù):(6,2)  
  3. print(round(4.50))   # 五舍六入:4  
  4. print(round(4.51))   #5 
  5. print(pow(10,2,3))  # 如果給了第三個參數(shù). 表示最后取余:1  
  6. print(sum([1,2,3,4,5,6,7,8,9,10]))  # 求和:55  
  7. print(min(5,3,9,12,7,2))  #求最小值:2  
  8. print(max(7,3,15,9,4,13))  #求最大值:15 

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

1. 序列

(1)列表和元組

  •  list() 將一個可迭代對象轉(zhuǎn)換成列表
  •  tuple() 將一個可迭代對象轉(zhuǎn)換成元組 
  1. print(list((1,2,3,4,5,6)))  #[1, 2, 3, 4, 5, 6]  
  2. print(tuple([1,2,3,4,5,6]))  #(1, 2, 3, 4, 5, 6) 

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

  •  reversed() 將一個序列翻轉(zhuǎn), 返回翻轉(zhuǎn)序列的迭代器
  •  slice() 列表的切片 
  1. lst = "你好啊"  
  2. it = reversed(lst)   # 不會改變原列表. 返回一個迭代器, 設(shè)計上的一個規(guī)則  
  3. print(list(it))  #['啊', '好', '你']  
  4. lst = [1, 2, 3, 4, 5, 6, 7]  
  5. print(lst[1:3:1])  #[2,3]  
  6. s = slice(1, 3, 1)  #  切片用的  
  7. print(lst[s])  #[2,3] 

(3)字符串

  •  str() 將數(shù)據(jù)轉(zhuǎn)化成字符串 
  1. print(str(123)+'456')  #123456  
  2.   format()     與具體數(shù)據(jù)相關(guān), 用于計算各種小數(shù), 精算等.  
  1. s = "hello world!"  
  2. print(format(s, "^20"))  #劇中  
  3. print(format(s, "<20"))  #左對齊  
  4. print(format(s, ">20"))  #右對齊  
  5. #     hello world!      
  6. # hello world!          
  7. #         hello world!  
  8. print(format(3, 'b' ))    # 二進(jìn)制:11  
  9. print(format(97, 'c' ))   # 轉(zhuǎn)換成unicode字符:a  
  10. print(format(11, 'd' ))   # ⼗進(jìn)制:11  
  11. print(format(11, 'o' ))   # 八進(jìn)制:13   
  12. print(format(11, 'x' ))   # 十六進(jìn)制(⼩寫字母):b  
  13. print(format(11, 'X' ))   # 十六進(jìn)制(大寫字母):B  
  14. print(format(11, 'n' ))   # 和d⼀樣:11 
  15. print(format(11))         # 和d⼀樣:11  
  16. print(format(123456789, 'e' ))      # 科學(xué)計數(shù)法. 默認(rèn)保留6位小數(shù):1.234568e+08  
  17. print(format(123456789, '0.2e' ))   # 科學(xué)計數(shù)法. 保留2位小數(shù)(小寫):1.23e+08  
  18. print(format(123456789, '0.2E' ))   # 科學(xué)計數(shù)法. 保留2位小數(shù)(大寫):1.23E+08  
  19. print(format(1.23456789, 'f' ))     # 小數(shù)點計數(shù)法. 保留6位小數(shù):1.234568  
  20. print(format(1.23456789, '0.2f' ))  # 小數(shù)點計數(shù)法. 保留2位小數(shù):1.23  
  21. print(format(1.23456789, '0.10f'))  # 小數(shù)點計數(shù)法. 保留10位小數(shù):1.2345678900  
  22. print(format(1.23456789e+3, 'F'))   # 小數(shù)點計數(shù)法. 很大的時候輸出INF:1234.567890 
  •  bytes() 把字符串轉(zhuǎn)化成bytes類型 
  1. bs = bytes("今天吃飯了嗎", encoding="utf-8" 
  2. print(bs)  #b'\xe4\xbb\x8a\xe5\xa4\xa9\xe5\x90\x83\xe9\xa5\xad\xe4\xba\x86\xe5\x90\x97'  
  3.    bytearray()    返回一個新字節(jié)數(shù)組. 這個數(shù)字的元素是可變的, 并且每個元素的值得范圍是[0,256)  
  4. ret = bytearray("alex" ,encoding ='utf-8' 
  5. print(ret[0])  #97  
  6. print(ret)  #bytearray(b'alex')  
  7. ret[0] = 65  #把65的位置A賦值給ret[0]  
  8. print(str(ret))  #bytearray(b'Alex') 
  •  ord() 輸入字符找?guī)ё址幋a的位置
  •  chr() 輸入位置數(shù)字找出對應(yīng)的字符
  •  ascii() 是ascii碼中的返回該值 不是就返回u 
  1. print(ord('a'))  # 字母a在編碼表中的碼位:97  
  2. print(ord('中'))  # '中'字在編碼表中的位置:20013  
  3. print(chr(65))  # 已知碼位,求字符是什么:A  
  4. print(chr(19999))  #丟 
  5. for i in range(65536):  #打印出0到65535的字符  
  6.     print(chr(i), end=" " 
  7. print(ascii("@"))  #'@' 
  •  repr() 返回一個對象的string形式 
  1. s = "今天\n吃了%s頓\t飯" % 3  
  2. print(s)#今天# 吃了3頓    飯  
  3. print(repr(s))   # 原樣輸出,過濾掉轉(zhuǎn)義字符 \n \t \r 不管百分號%  
  4. #'今天\n吃了3頓\t飯' 

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

  •  字典:dict 創(chuàng)建一個字典
  •  集合:set 創(chuàng)建一個集合

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

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

  •  len() 返回一個對象中的元素的個數(shù)
  •  sorted() 對可迭代對象進(jìn)行排序操作 (lamda)

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

  •  Iterable: 可迭代對象
  •  key: 排序規(guī)則(排序函數(shù)), 在sorted內(nèi)部會將可迭代對象中的每一個元素傳遞給這個函數(shù)的參數(shù). 根據(jù)函數(shù)運算的結(jié)果進(jìn)行排序
  •  reverse: 是否是倒敘. True: 倒敘, False: 正序 
  1. lst = [5,7,6,12,1,13,9,18,5]  
  2. lst.sort()  # sort是list里面的一個方法  
  3. print(lst)  #[1, 5, 5, 6, 7, 9, 12, 13, 18]  
  4. ll = sorted(lst) # 內(nèi)置函數(shù). 返回給你一個新列表  新列表是被排序的  
  5. print(ll)  #[1, 5, 5, 6, 7, 9, 12, 13, 18] 
  6. l2 = sorted(lst,reverse=True)  #倒序  
  7. print(l2)  #[18, 13, 12, 9, 7, 6, 5, 5, 1] 

#根據(jù)字符串長度給列表排序 

  1. lst = ['one', 'two', 'three', 'four', 'five', 'six']  
  2. def f(s):  
  3.     return len(s)  
  4. l1 = sorted(lst, key=f, )  
  5. print(l1)  #['one', 'two', 'six', 'four', 'five', 'three'] 
  •  enumerate() 獲取集合的枚舉對象 
  1. lst = ['one','two','three','four','five']  
  2. for index, el in enumerate(lst,1):    # 把索引和元素一起獲取,索引默認(rèn)從0開始. 可以更改  
  3.     print(index)  
  4.     print(el)  
  5. # 1  
  6. # one  
  7. # 2  
  8. # two  
  9. # 3  
  10. # three  
  11. # 4  
  12. # four  
  13. # 5  
  14. # five 
  •  all() 可迭代對象中全部是True, 結(jié)果才是True
  •  any() 可迭代對象中有一個是True, 結(jié)果就是True 
  1. print(all([1,'hello',True,9]))  #True  
  2. print(any([0,0,0,False,1,'good']))  #True 
  •  zip() 函數(shù)用于將可迭代的對象作為參數(shù), 將對象中對應(yīng)的元素打包成一個元組, 然后返回由這些元組組成的列表. 如果各個迭代器的元素個數(shù)不一致, 則返回列表長度與最短的對象相同 
  1. lst1 = [1, 2, 3, 4, 5, 6]  
  2. lst2 = ['醉鄉(xiāng)民謠', '驢得水', '放牛班的春天', '美麗人生', '辯護人', '被嫌棄的松子的一生']  
  3. lst3 = ['美國', '中國', '法國', '意大利', '韓國', '日本']  
  4. print(zip(lst1, lst1, lst3))  #<zip object at 0x00000256CA6C7A88>  
  5. for el in zip(lst1, lst2, lst3):  
  6.     print(el)  
  7. # (1, '醉鄉(xiāng)民謠', '美國')  
  8. # (2, '驢得水', '中國')  
  9. # (3, '放牛班的春天', '法國')  
  10. # (4, '美麗人生', '意大利')  
  11. # (5, '辯護人', '韓國')  
  12. # (6, '被嫌棄的松子的一生', '日本') 
  •  fiter() 過濾 (lamda)

語法:fiter(function. Iterable)

function: 用來篩選的函數(shù). 在filter中會自動的把iterable中的元素傳遞給function. 然后根據(jù)function返回的True或者False來判斷是否保留留此項數(shù)據(jù) , Iterable: 可迭代對象 

  1. def func(i):    # 判斷奇數(shù)  
  2.     return i % 2 == 1  
  3.     lst = [1,2,3,4,5,6,7,8,9]  
  4. l1 = filter(func, lst)  #l1是迭代器  
  5. print(l1)  #<filter object at 0x000001CE3CA98AC8>  
  6. print(list(l1))  #[1, 3, 5, 7, 9] 
  •  map() 會根據(jù)提供的函數(shù)對指定序列列做映射(lamda)

語法 : map(function, iterable) 

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

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

和作用域相關(guān)

  •  locals() 返回當(dāng)前作用域中的名字
  •  globals() 返回全局作用域中的名字 
  1. def func():  
  2.     a = 10  
  3.     print(locals())  # 當(dāng)前作用域中的內(nèi)容  
  4.     print(globals())  # 全局作用域中的內(nèi)容  
  5.     print("今天內(nèi)容很多")  
  6. func()  
  7. # {'a': 10}  
  8. # {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':   
  9. <_frozen_importlib_external.SourceFileLoader object at 0x0000026F8D566080>,   
  10. # '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins'   
  11. # (built-in)>, '__file__': 'D:/pycharm/練習(xí)/week03/new14.py', '__cached__': None,  
  12. #  'func': <function func at 0x0000026F8D6B97B8> 
  13. # 今天內(nèi)容很多 

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

  •  range() 生成數(shù)據(jù)
  •  next() 迭代器向下執(zhí)行一次, 內(nèi)部實際使⽤用了__ next__()⽅方法返回迭代器的下一個項目
  •  iter() 獲取迭代器, 內(nèi)部實際使用的是__ iter__()⽅方法來獲取迭代器 
  1. for i in range(15,-1,-5):  
  2.     print(i)  
  3. # 15  
  4. # 10  
  5. # 5  
  6. # 0  
  7. lst = [1,2,3,4,5]  
  8. it = iter(lst)  #  __iter__()獲得迭代器  
  9. print(it.__next__())  #1  
  10. print(next(it)) #2  __next__()    
  11. print(next(it))  #3  
  12. print(next(it))  #4 

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

  •  eval() 執(zhí)行字符串類型的代碼. 并返回最終結(jié)果
  •  exec() 執(zhí)行字符串類型的代碼
  •  compile() 將字符串類型的代碼編碼. 代碼對象能夠通過exec語句來執(zhí)行或者eval()進(jìn)行求值 
  1. s1 = input("請輸入a+b:")  #輸入:8+9  
  2. print(eval(s1))  # 17 可以動態(tài)的執(zhí)行代碼. 代碼必須有返回值  
  3. s2 = "for i in range(5): print(i)"  
  4. a = exec(s2) # exec 執(zhí)行代碼不返回任何內(nèi)容  
  5. # 0  
  6. # 1  
  7. # 2  
  8. # 3  
  9. # 4  
  10. print(a)  #None  
  11. # 動態(tài)執(zhí)行代碼  
  12. exec("""  
  13. def func():  
  14.     print(" 我是周杰倫")  
  15. """ )  
  16. func()  #我是周杰倫  
  1. code1 = "for i in range(3): print(i)"  
  2. com = compile(code1, "", mode="exec")   # compile并不會執(zhí)行你的代碼.只是編譯  
  3. exec(com)   # 執(zhí)行編譯的結(jié)果  
  4. # 0  
  5. # 1  
  6. # 2  
  7. code2 = "5+6+7"  
  8. com2 = compile(code2, "", mode="eval" 
  9. print(eval(com2))  # 18  
  10. code3 = "name = input('請輸入你的名字:')"  #輸入:hello  
  11. com3 = compile(code3, "", mode="single" 
  12. exec(com3)  
  13. print(name)  #hello 

輸入輸出

  •  print() : 打印輸出
  •  input() : 獲取用戶輸出的內(nèi)容 
  1. print("hello", "world", sep="*"end="@") # sep:打印出的內(nèi)容用什么連接,end:以什么為結(jié)尾  
  2. #hello*world@ 

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

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

  1. s = 'alex'  
  2. print(hash(s))  #-168324845050430382  
  3. lst = [1, 2, 3, 4, 5]  
  4. print(hash(lst))  #報錯,列表是不可哈希的  
  5.   id() :  獲取到對象的內(nèi)存地址  
  6. s = 'alex'  
  7. print(id(s))  #2278345368944 

文件操作相關(guān)

  •  open() : 用于打開一個文件, 創(chuàng)建一個文件句柄 
  1. f = open('file',mode='r',encoding='utf-8' 
  2. f.read()  
  3. f.close() 

模塊相關(guān)

  •  __ import__() : 用于動態(tài)加載類和函數(shù) 
  1. # 讓用戶輸入一個要導(dǎo)入的模塊  
  2. import os  
  3. name = input("請輸入你要導(dǎo)入的模塊:")  
  4. __import__(name)    # 可以動態(tài)導(dǎo)入模塊 

幫  助

  •  help() : 函數(shù)用于查看函數(shù)或模塊用途的詳細(xì)說明
  1. print(help(str))  #查看字符串的用途 

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

  •  callable() : 用于檢查一個對象是否是可調(diào)用的. 如果返回True, object有可能調(diào)用失敗, 但如果返回False. 那調(diào)用絕對不會成功 
  1. a = 10  
  2. print(callable(a))  #False  變量a不能被調(diào)用  
  3.  
  4. def f():  
  5.     print("hello")  
  6.     print(callable(f))   # True 函數(shù)是可以被調(diào)用的 

查看內(nèi)置屬性

  •  dir() : 查看對象的內(nèi)置屬性, 訪問的是對象中的__dir__()方法
  1. print(dir(tuple))  #查看元組的方法  

 

責(zé)任編輯:龐桂玉 來源: Python編程
相關(guān)推薦

2020-09-25 16:20:21

Python內(nèi)置函數(shù)字符串

2023-12-22 15:44:43

2020-06-24 07:44:12

Python數(shù)據(jù)技術(shù)

2021-03-16 10:12:24

python內(nèi)置函數(shù)

2023-04-09 23:09:59

Go語言函數(shù)

2022-05-13 09:55:19

Python內(nèi)置函數(shù)

2024-01-24 13:14:00

Python內(nèi)置函數(shù)工具

2024-04-29 14:58:48

Python內(nèi)置函數(shù)

2023-09-17 23:32:03

內(nèi)置函數(shù)編程Python

2023-10-09 22:30:58

Python函數(shù)

2021-09-15 09:20:37

Python函數(shù)代碼

2019-02-18 15:05:16

Python內(nèi)置函數(shù)索引

2020-04-16 09:50:14

Python 開發(fā)效率

2021-04-26 05:35:22

Python內(nèi)置函數(shù)

2022-04-04 09:12:18

Python內(nèi)置函數(shù)

2021-06-09 07:32:18

C++內(nèi)置函數(shù)函數(shù)傳參

2020-02-10 16:07:42

工具包

2023-05-03 20:53:48

2018-05-18 09:18:00

數(shù)據(jù)分析報告數(shù)據(jù)收集

2025-01-06 12:00:00

Python函數(shù)內(nèi)置函數(shù)
點贊
收藏

51CTO技術(shù)棧公眾號