1. 程式人生 > 程式設計 >python中68個內建函式的總結與介紹

python中68個內建函式的總結與介紹

python內建函式

內建函式就是python給你提供的,拿來直接用的函式,比如print.,input等. 截止到python版本3.6.2 python一共提供了68個內建函式.

68個內建函式

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()

1. 和數字相關

(1) 資料型別

1) bool : 布林型(True,False)

2) int : 整型(整數)

3) float : 浮點型(小數)

4) complex : 複數

(2) 進位制轉換

1) bin() 將給的引數轉換成二進位制

2) otc() 將給的引數轉換成八進位制

3) hex() 將給的引數轉換成十六進位制

print(bin(10)) # 二進位制:0b1010
print(hex(10)) # 十六進位制:0xa
print(oct(10)) # 八進位制:0o12

(3) 數學運算

1) abs() 返回絕對值

2) divmode() 返回商和餘數

3) round() 四捨五入

4) pow(a,b) 求a的b次冪,如果有三個引數. 則求完次冪後對第三個數取餘

5) sum() 求和

6) min() 求最小值

7) max() 求最大值

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

2. 和資料結構相關

(1) 序列

1) 列表和元組

  list() 將一個可迭代物件轉換成列表

  tuple() 將一個可迭代物件轉換成元組

print(list((1,6))) #[1,6]
print(tuple([1,6])) #(1,6)

       相關內建函式

  reversed() 將一個序列翻轉,返回翻轉序列的迭代器

  slice() 列表的切片

lst = "你好啊"
it = reversed(lst)  # 不會改變原列表. 返回一個迭代器,設計上的一個規則
print(list(it)) #['啊','好','你']

lst = [1,7]
print(lst[1:3:1]) #[2,3]

s = slice(1,1) # 切片用的
print(lst[s]) #[2,3]

3) 字串

  str() 將資料轉化成字串

print(str(123)+'456') #123456

  format()     與具體資料相關,用於計算各種小數,精算等.

s = "hello world!"
print(format(s,"^20")) #劇中
print(format(s,"<20")) #左對齊
print(format(s,">20")) #右對齊
#   hello world!  
# hello world!    
#     hello world!

print(format(3,'b' ))  # 二進位制:11
print(format(97,'c' ))  # 轉換成unicode字元:a
print(format(11,'d' ))  # ⼗進位制:11
print(format(11,'o' ))  # 八進位制:13 
print(format(11,'x' ))  # 十六進位制(⼩寫字母):b
print(format(11,'X' ))  # 十六進位制(大寫字母):B
print(format(11,'n' ))  # 和d⼀樣:11
print(format(11))     # 和d⼀樣:11

print(format(123456789,'e' ))   # 科學計數法. 預設保留6位小數:1.234568e+08
print(format(123456789,'0.2e' ))  # 科學計數法. 保留2位小數(小寫):1.23e+08
print(format(123456789,'0.2E' ))  # 科學計數法. 保留2位小數(大寫):1.23E+08
print(format(1.23456789,'f' ))   # 小數點計數法. 保留6位小數:1.234568
print(format(1.23456789,'0.2f' )) # 小數點計數法. 保留2位小數:1.23
print(format(1.23456789,'0.10f')) # 小數點計數法. 保留10位小數:1.2345678900
print(format(1.23456789e+3,'F'))  # 小數點計數法. 很大的時候輸出INF:1234.567890

bytes() 把字串轉化成bytes型別

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()  返回一個新位元組陣列. 這個數字的元素是可變的,並且每個元素的值得範圍是[0,256)

ret = bytearray("alex",encoding ='utf-8')
print(ret[0]) #97
print(ret) #bytearray(b'alex')
ret[0] = 65 #把65的位置A賦值給ret[0]
print(str(ret)) #bytearray(b'Alex')

ord() 輸入字元找帶字元編碼的位置

chr() 輸入位置數字找出對應的字元

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

print(ord('a')) # 字母a在編碼表中的碼位:97
print(ord('中')) # '中'字在編碼表中的位置:20013

print(chr(65)) # 已知碼位,求字元是什麼:A
print(chr(19999)) #丟

for i in range(65536): #打印出0到65535的字元
  print(chr(i),end=" ")

print(ascii("@")) #'@'

repr() 返回一個物件的string形式

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

(2) 資料集合

  1) 字典

  dict 建立一個字典

  2) 集合

  set 建立一個集合

frozenset() 建立一個凍結的集合. 凍結的集合不能進行新增和刪除操作

(3) 相關內建函式

  len() 返回一個物件中的元素的個數

  sorted() 對可迭代物件進行排序操作 (lamda)

  語法:

  sorted(Iterable,key=函式(排序規則),reverse=False)

Iterable: 可迭代物件

key: 排序規則(排序函式),在sorted內部會將可迭代物件中的每一個元素傳遞給這個函式的引數. 根據函式運算的結果進行排序

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

lst = [5,1,13,18,5]
lst.sort() # sort是list裡面的一個方法
print(lst) #[1,18]

ll = sorted(lst) # 內建函式. 返回給你一個新列表 新列表是被排序的
print(ll) #[1,18]

l2 = sorted(lst,reverse=True) #倒序
print(l2) #[18,1]

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

enumerate() 獲取集合的列舉物件

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

 all() 可迭代物件中全部是True,結果才是True

 any() 可迭代物件中有一個是True,結果就是True

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

zip() 函式用於將可迭代的物件作為引數,將物件中對應的元素打包成一個元組,然後返回由這些元組組成的列表. 如果各個迭代器的元素個數不一致,則返回列表長度與最短的物件相同

lst1 = [1,6]
lst2 = ['醉鄉民謠','驢得水','放牛班的春天','美麗人生','辯護人','被嫌棄的松子的一生']
lst3 = ['美國','中國','法國','義大利','韓國','日本']
print(zip(lst1,lst1,lst3)) #<zip object at 0x00000256CA6C7A88>
for el in zip(lst1,lst2,lst3):
  print(el)
# (1,'醉鄉民謠','美國')
# (2,'中國')
# (3,'法國')
# (4,'義大利')
# (5,'韓國')
# (6,'被嫌棄的松子的一生','日本')

fiter() 過濾 (lamda)

語法:

  • fiter(function. Iterable)
  • function: 用來篩選的函式. 在filter中會自動的把iterable中的元素傳遞給function. 然後根據function返回的True或者False來判斷是否保留留此項資料,Iterable: 可迭代物件
def func(i):  # 判斷奇數
  return i % 2 == 1
lst = [1,9]
l1 = filter(func,lst) #l1是迭代器
print(l1) #<filter object at 0x000001CE3CA98AC8>
print(list(l1)) #[1,9]

map() 會根據提供的函式對指定序列列做對映(lamda)

語法 : map(function,iterable) 可以對可迭代物件中的每一個元素進行對映. 分別去執行 function

def f(i):
  return i
lst = [1,]
it = map(f,lst) # 把可迭代物件中的每一個元素傳遞給前面的函式進行處理. 處理的結果會返回成迭代器
print(list(it)) #[1,7]

3. 和作用域相關

locals() 返回當前作用域中的名字

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

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

4. 和迭代器/生成器相關

range() 生成資料

next() 迭代器向下執行一次,內部實際使⽤用了__ next__()⽅方法返回迭代器的下一個專案

iter() 獲取迭代器,內部實際使用的是__ iter__()⽅方法來獲取迭代器

for i in range(15,-1,-5):
  print(i)
# 15
# 10
# 5
# 0

lst = [1,5]
it = iter(lst) # __iter__()獲得迭代器
print(it.__next__()) #1
print(next(it)) #2 __next__() 
print(next(it)) #3
print(next(it)) #4

5. 字串型別程式碼的執行

eval() 執行字串型別的程式碼. 並返回最終結果

exec() 執行字串型別的程式碼

compile() 將字串型別的程式碼編碼. 程式碼物件能夠通過exec語句來執行或者eval()進行求值

s1 = input("請輸入a+b:") #輸入:8+9
print(eval(s1)) # 17 可以動態的執行程式碼. 程式碼必須有返回值

s2 = "for i in range(5): print(i)"
a = exec(s2) # exec 執行程式碼不返回任何內容
# 0
# 1
# 2
# 3
# 4
print(a) #None

# 動態執行程式碼
exec("""
def func():
  print(" 我是周杰倫")
""" )
func() #我是周杰倫

6. 輸入輸出

print() : 列印輸出

input() : 獲取使用者輸出的內容

print("hello","world",sep="*",end="@") # sep:打印出的內容用什麼連線,end:以什麼為結尾
#hello*world@

7. 記憶體相關

hash() : 獲取到物件的雜湊值(int,str,bool,tuple). hash演算法:(1) 目的是唯一性 (2) dict 查詢效率非常高,hash表.用空間換的時間 比較耗費記憶體

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

lst = [1,5]
print(hash(lst)) #報錯,列表是不可雜湊的
  id() : 獲取到物件的記憶體地址

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

8.檔案操作相關

open() : 用於開啟一個檔案,建立一個檔案控制代碼

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

9. 模組相關

__ import__() : 用於動態載入類和函式

# 讓使用者輸入一個要匯入的模組
import os
name = input("請輸入你要匯入的模組:")
__import__(name)  # 可以動態匯入模組

10. 幫助

help() : 函式用於檢視函式或模組用途的詳細說明

print(help(str)) #檢視字串的用途

11. 呼叫相關

callable() : 用於檢查一個物件是否是可呼叫的. 如果返回True,object有可能呼叫失敗,但如果返回False. 那呼叫絕對不會成功

a = 10
print(callable(a)) #False 變數a不能被呼叫
#
def f():
  print("hello")
print(callable(f))  # True 函式是可以被呼叫的

12. 檢視內建屬性

dir() : 檢視物件的內建屬性,訪問的是物件中的__dir__()方法

print(dir(tuple)) #檢視元組的方法

更多關於python內建函式介紹請檢視下面的相關連結