Python 函數合集:足足 68 個內置函數請收好

2021-03-02 Python開發者

(給Python開發者加星標,提升Python技能)

來源:pypypypy 

www.cnblogs.com/pypypy/p/12011506.html

內置函數就是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. 數據類型

bool : 布爾型(True,False)

int : 整型(整數)

float : 浮點型(小數)

complex : 複數

2. 進位轉換

bin() 將給的參數轉換成二進位

otc() 將給的參數轉換成八進位

hex() 將給的參數轉換成十六進位

print(bin(10))  print(hex(10))  print(oct(10))  

3. 數學運算

print(abs(-2))  print(divmod(20,3)) print(round(4.50))   print(round(4.51))   print(pow(10,2,3))  print(sum([1,2,3,4,5,6,7,8,9,10]))  print(min(5,3,9,12,7,2))  print(max(7,3,15,9,4,13))  

1. 序列

list() 將一個可迭代對象轉換成列表

tuple() 將一個可迭代對象轉換成元組

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

(2)相關內置函數

lst = "你好啊"it = reversed(lst)   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])  

(3)字符串

print(str(123)+'456')    format()     與具體數據相關, 用於計算各種小數, 精算等.

s = "hello world!"print(format(s, "^20"))  print(format(s, "<20"))  print(format(s, ">20"))  print(format(3, 'b' ))    print(format(97, 'c' ))   print(format(11, 'd' ))   print(format(11, 'o' ))   print(format(11, 'x' ))   print(format(11, 'X' ))   print(format(11, 'n' ))   print(format(11))         print(format(123456789, 'e' ))      print(format(123456789, '0.2e' ))   print(format(123456789, '0.2E' ))   print(format(1.23456789, 'f' ))     print(format(1.23456789, '0.2f' ))  print(format(1.23456789, '0.10f'))  print(format(1.23456789e+3, 'F'))   

bs = bytes("今天吃飯了嗎", encoding="utf-8")print(bs)     bytearray()    返回一個新字節數組. 這個數字的元素是可變的, 並且每個元素的值得範圍是[0,256)ret = bytearray("alex" ,encoding ='utf-8')print(ret[0])  print(ret)  ret[0] = 65  print(str(ret))  

print(ord('a'))  print(ord('中'))  print(chr(65))  print(chr(19999))  for i in range(65536):      print(chr(i), end=" ")print(ascii("@"))  #'@'

s = "今天\n吃了%s頓\t飯" % 3print(s)print(repr(s))   

2. 數據集合

frozenset() 創建一個凍結的集合,凍結的集合不能進行添加和刪除操作。

3. 相關內置函數

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

Iterable: 可迭代對象

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

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

lst = [5,7,6,12,1,13,9,18,5]lst.sort()  print(lst)  ll = sorted(lst) print(ll)  l2 = sorted(lst,reverse=True)  print(l2)  

#根據字符串長度給列表排序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']

lst = ['one','two','three','four','five']for index, el in enumerate(lst,1):        print(index)    print(el)

all() 可迭代對象中全部是True, 結果才是True

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

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

lst1 = [1, 2, 3, 4, 5, 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(function. Iterable)

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

def func(i):    # 判斷奇數    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(function, iterable) 

可以對可迭代對象中的每一個元素進行映射. 分別去執行 function

def f(i):    return ilst = [1,2,3,4,5,6,7,]it = map(f, lst) 

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>}# 今天內容很多

range() 生成數據

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

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

for i in range(15,-1,-5):    print(i)lst = [1,2,3,4,5]it = iter(lst)  print(it.__next__())  print(next(it)) print(next(it))  print(next(it))  

s1 = input("請輸入a+b:")  print(eval(s1))  s2 = "for i in range(5): print(i)"a = exec(s2) print(a)  exec("""def func():    print(" 我是周杰倫")""" )func()  

code1 = "for i in range(3): print(i)"com = compile(code1, "", mode="exec")   exec(com)   code2 = "5+6+7"com2 = compile(code2, "", mode="eval")print(eval(com2))  code3 = "name = input('請輸入你的名字:')"  com3 = compile(code3, "", mode="single")exec(com3)print(name)  

print() : 列印輸出

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

print("hello", "world", sep="*", end="@") 

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

s = 'alex'print(hash(s))  lst = [1, 2, 3, 4, 5]print(hash(lst))    id() :  獲取到對象的內存地址s = 'alex'print(id(s))  

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

__ import__() : 用於動態加載類和函數

import osname = input("請輸入你要導入的模塊:")__import__(name)    

a = 10print(callable(a))  def f():    print("hello")    print(callable(f))   

覺得本文對你有幫助?請分享給更多人

關注「Python開發者」加星標,提升Python技能

好文章,我在看❤️

相關焦點

  • Python 函數合集:足足 68 個內置函數,請收好
    python給你提供的, 拿來直接用的函數,比如print.截止到python版本3.6.2 python一共提供了68個內置函數。#68個內置函數# abs()   dict()   help()   min()   setattr()# all()   dir()   hex()   next()   slice() # any()   divmod
  • Python內置函數一覽表
    如果你熟悉 Shell 編程,了解什麼是 Shell 內置命令,那麼你也很容易理解什麼是 Python 內置函數,它們的概念是類似的。將使用頻繁的代碼段封裝起來,並給它起一個名字,以後使用的時候只要知道名字就可以,這就是函數。函數就是一段封裝好的、可以重複使用的代碼,它使得我們的程序更加模塊化,不需要編寫大量重複的代碼。
  • Python必學基礎:12大類68個內置函數
    內置函數就是Python給你提供的,拿來直接用的函數,比如print.,input等。       截止到python版本3.6.2 ,python一共提供了68個內置函數,具體如下👇abs()           dict()        help()         min()         setattr()all()
  • 這68個Python內置函數,建議你吃透!
    內置函數就是Python給你提供的, 拿來直接用的函數,比如print,input等。截止到python版本3.6.2 ,一共提供了68個內置函數,具體如下👇abs()           dict()        help()         min()         setattr()all()           dir()
  • Python打基礎一定要吃透這68個內置函數
    作者:pypypypy來源:博客園內置函數就是Python給你提供的,拿來直接用的函數,比如print.,input等。截止到python版本3.6.2 ,python一共提供了68個內置函數,具體如下👇abs()           dict()        help()         min()         setattr()all()           dir()
  • 柳小白Python學習筆記 8 函數(function)之內置函數
    函數是組織好的,可重複使用的,用來實現單一或相關聯功能的代碼段。python提供了很多內置函數,當然我們也可以自定義函數。今天主要學習一些內置函數的用法。python裡內置了很多函數,這些函數可以直接調用。
  • Python中有哪些內置函數呢?以及內置函數實例
    >Python中有哪些內置函數呢?常見簡單內置函數:len 求長度min 求最小值max 求最大值sorted 排序reversed 反向sum 求和高級內置函數enumerate 返回一個可以枚舉的對象eval 取出 字符串中的內容,將字符串str當成有效的表達式來求指並返回計算結果exec 執行字符串或complie方法編譯過的字符串
  • python教程:3個非常有用的內置函數
    這三個內置函數還是非常有用的,在工作中用的還不少,順手,下面一一進行介紹 1、filter 語法:filter
  • python 內置函數
    列舉部分python內置函數描述abs() 函數返回數字的絕對值
  • python eval()內置函數
    python有一個內置函數eval(),可以將字符串進行運行。
  • 為什麼說python內置函數並不是萬能的?
    PS:內置函數 built-in function 和內置類型 built-in type 很相似,但 list() 實際是一種內置類型而不是內置函數。我曾對這兩種易混淆的概念做過辨析,請查看這篇文章。為了方便理解與表述,以下統稱為內置函數。1、內置函數的查找優先級最低內置函數的名稱並不屬於關鍵字,它們是可以被重新賦值的。
  • python的內置函數:int()轉換成整型
    在python中是利用內置函數int()來將一個對象轉換成整型。python的內置函數int的使用1.內置函數int()語法classint(x,base=10),其中x為一個字符串或數字,base來表示x是以什麼進位的數據來表示的。
  • python中str內置函數用法總結
    大家在使用python的過程中,應該在敲代碼的時候經常遇到str內置函數,為了防止大家搞混,本文整理歸納了str內置函數。
  • Python中10個常用的內置函數
    大家好,我是小張在 3.8 版本中,Python 解釋器有近 69 個內置函數可供使用,有了它們能極大地提高編碼效率,數量雖然不少,但在日常搬磚中只用到其中一部分,根據使用頻率和用法,這裡列出來幾個本人認為不錯的內置函數,結合一些例子介紹給大家
  • Python 中 10 個常用的內置函數
    大家好,我是安果!在 3.8 版本中,Python 解釋器有近 69 個內置函數可供使用,有了它們能極大地提高編碼效率數量雖然不少,但在日常搬磚中只用到其中一部分,根據使用頻率和用法,這裡列出來幾個本人認為不錯的內置函數,結合一些例子介紹給大家complex()
  • python內置函數format的使用方法
    Java中的formatdouble totalMoney = 100.23456;String totalM = String.format("%.2f",totalMoney);得到的結果是100.23python內置函數format1.基本語法format 函數可以接受不限個參數,位置可以不按順序
  • python的內置函數:sum求和函數
    前言看到sum,我們就知道這是一個求和函數,無論是java、javascript還是mysql中,求和是簡單的,但在python中,可以進行一些複雜的元組求和,具體是怎樣的呢?python中的sum求和函數1.sum的使用語法sum(iterable[, start]) iterable -- 可迭代對象,如:列表、元組、集合。
  • Python 69個內置函數分8類總結,這樣記更方便!
    >內置函數Python3解釋器中內置了69個常用函數,屬於底層的函數,它們到處可用。1 類型相關69個內置函數中,與類型相關的指,把入參包裝為某種類型,這樣的內置函數包括:bool()  #d布爾型int()  #d整形str()  #d字符型tuple() #d元包型dict() #d字典型list() #d列表型
  • 打基礎一定要吃透這12類 Python 內置函數
    內置函數就是python給你提供的, 拿來直接用的函數,比如print.,input等。截止到python版本3.6.2 python一共提供了68個內置函數,我將它們分成 12 類,方便你學習。1. 和數字相關1.
  • python(內置函數, 模塊)打補丁, 兼容py2、3
    py2官方已不在維護, 所以將項目升級到py3, 但是項目也不是一行兩行的事, 並且項目還在使用, 所以必須要兼容py2, 升級到py3  所以就有了以下常見問題, 比如, py2的內置函數py3已不使用, py2的內置模塊py3已經改名....