🍖內置函數

一.什麼是內置函數

  • 解釋器自帶的函數就是內置函數

  • 內置函數查看方法 print(dir(__builtins__))

print(len(dir(__builtins__)))  # 153個

二.常見內置函數

img

ps : 工廠函數 : int float str list tuple dict set bool byteshtml

三.經常使用內置函數介紹

👉部分經常使用內置函數在這👈: max min sorted map reduce filterpython

一、abs( ) : 絕對值

print(abs(-5))  # 變成正數

二、all( ) : 判斷

  • 一個爲假,就爲假 (0、空、None、Flase)
  • 全部元素的布爾值爲真,最終結果才爲真
print(all([1,'a',0]))  # False
print(all([1,2,[]]))   # False
  • 傳給 all 的可迭代對象若是爲空,最終結果爲真
print(all(''))   # True
print(all([]))   # True

三、any( ) : 判斷

  • 但凡是有一個爲真,就爲真
print(any([0,'',None,1]))  # True
  • 傳給 any 的可迭代對象若是爲空,最終結果爲假
print(any([]))    # False
print(any(''))    # False

四、進制轉換

print(bin(11))     # 10--->2
print(oct(11))     # 10--->8
print(hex(11))     # 10--->16

五、bool( ) : 布爾值

print(bool(0))     #0, None,空的布爾值爲假

六、.encode( ) : 轉類型

  • 編碼, 轉成 "bytes" 類型
res = '你好songhaiixng'.encode('utf-8')
print(res)   # b'\xe4\xbd\xa0\xe5\xa5\xbdsonghaiixng'

res = bytes('你好songhaixing',encoding='utf-8')
print(res)   # b'\xe4\xbd\xa0\xe5\xa5\xbdsonghaixing'

七、callable( ) : 調用

  • 判斷是否能夠調用
def func():
    pass
print(callable(func))         # True
print(callable('ss'.strip))   # True
print(callable('dac'.split))  # False
print(callable(123))          # False

八、ASCLL錶轉化

print(chr(90))   #按照表十進制轉化成字符
print(ord('x'))  #按照表十進制轉化成數字

九、dir( ) : 查看調用對象

  • 查看某個對象能夠調用的方式
print(dir('song'))  # [打印出一堆的調用方法]

十、divmod( ) : 除 餘

print(divmod(10,3))  #(3,1)--->10除於3餘1
print(divmod(10,2))  #(5,0)--->10除於2餘0

十一、eval( ) : 字符串內表達式運算

  • 將字符串裏面的表達式拿出來運算一下, 並拿到運算的結果
🍔數學表達式
res = eval('2**3')
print(res)          # 8

🍔列表
res = eval('[1,2,3,4.5,5]')
print(res)          # [1, 2, 3, 4.5, 5]
print(res[2])       # 3

🍔字典
res = eval("{'name':'shawn','age':18,'sex':'man'}")
print(res)          # {'name': 'shawn', 'age': 18, 'sex': 'man'}
print(res["name"])  # shawn
  • 文件存取示例 (文件拿出來是字符串, 使用 eval() 將其轉成字典)
with open(r"aaa.txt","at",encoding="utf-8")as f:
    f.write('{"name":"shawn","age":10,"sex":"man"}\n')
    f.write('{"name":"song","age":18,"sex":"woman"}\n')
    f.write('{"name":"xing","age":14,"sex":"man"}\n')

l = []
with open(r"aaa.txt","rt",encoding="utf-8")as f:
    for i in f:
        line = i.strip('\n')
        res = eval(line)
        l.append(res)

print(l)
'''
[{'name': 'shawn', 'age': 10, 'sex': 'man'},\
  {'name': 'song', 'age': 18, 'sex': 'woman'},\
   {'name': 'xing', 'age': 14, 'sex': 'man'}]
'''
print(type(l))       # <class dict>
print(l[0]["name"])  # shawn

十二、frozenset( ) : 不可變集合, 凍結集合

  • 製做不可變的集合
fset = frozenset({1,2,3})
print(fset)        # frozenset({1, 2, 3})
print(type(fset))  # <class 'frozenset'>

1三、globals( ) : 全局做用域中的綁定關係

  • 查看全局做用域中名字與值得綁定關係
  • locals( ) : 局部 (當前位置的)
🍔當都處於全局名稱空間調用查看時,查看的效果是同樣的
x = 111111
print(globals()) # [一堆綁定關係]
print(locals())  # [一堆綁定關係]

🍔當在函數內部使用 "locals()" 查看時, 獲得的就是函數內部名稱空間的綁定關係
def aa():
    x = 111
    y = 222
    print(locals())

aa()  #{'x': 111, 'y': 222}

1四、help( ) : 顯示幫助信息

def func():
    """
    幫助信息
    :return:
    """
    pass
print(help(func)) # [顯示裏面的幫助文檔]
print(help(max))

1五、len( ) : 長度

  • 自定調用 "__len__" 功能
print(len({'x':1,'y':2}))     # 2
print({'x':1,'y':2}.__len__)  # 2

1六、iter( ) : 迭代器

  • 自定調用 "__iter__" 功能
res = iter('song')
print(next(res))  # s
print(next(res))  # o
print(next(res))  # n
.......

1七、pow( ) : 平方取餘

print(pow(10, 2))     # 100   10**2------>100
print(pow(2,3,3))     # 2     2**3 % 3--->餘 2
print(pow(10, 2, 3))  # 1     10**2 % 3-->餘 1

1八、slice( ) : 切片

  • 建立一個切片模板(對象),之後能夠直接拿過來用
🍔建立切片對象
res = slice(1, 5, 2)  

🍔直接使用建立好的來切
l = [1, 2, 3, 4, 5, 6, 7, 8]
print(l[res])     #[2, 4]

t = (5, 14, 7, 8, 9, 5, 4, 2)
print(t[res])     #(14, 8)

1九、sum( ) : 求和

print(sum([1,2,3,4,5]))    # 15

20、zip( ) : (拉鍊函數) 左右對應

left = 'hello'
right = (1,2,3,)    

res = zip(left,right)
print(res)        # <zip object at 0x0000016FC23A0748>
print(type(res))  # <class 'zip'>
print(list(res))  # [('h', 1), ('e', 2), ('l', 3)]

2一、__import__ : 轉模塊

  • 通常用於從文件中讀取字符串, 將其轉換成模塊的形式
  • 拿到的返回值能夠進行模塊的操做
with open('m',mode='rt',encoding='utf-8') as f:
    module=f.read()          # 這裏拿到的是字符串
    time=__import__(module)  # __import__("time") 以字符串形式導入模塊
    time.sleep(3)
    print(time.time())

2二、reversed( ) : 倒序

  • 將一個有序對象倒過來排序 (單純的倒過來)
res = reversed((2,3,65,765,23,20))
res2 = reversed([4,6,2,7,9,0,3,1])
print(tuple(res))  # (20, 23, 765, 65, 3, 2)
print(list(res2))  # [1, 3, 0, 9, 7, 2, 6, 4]

2三、hash( ) : 哈希值

  • 返回傳入對象的 hash
  • 傳入的是可 hash 類型, 也就是不可變類型
print(hash(1231))           # 1231
print(hash("派大星"))        # 4444534694763505378
print(hash((1,2,3,4,"a")))  # 4233406373922709203
print(hash(2.5))            # 1152921504606846978

print(hash(['海綿寶寶',12]))  # 報錯 : TypeError

東風夜放花千樹 更吹落 星如雨 寶馬雕車香滿路

相關文章
相關標籤/搜索