你真的懂Python的內置函數嗎?68個內置函數大總結!

學了快一年的Python了,突然發現,內置函數能夠大大的加快開發時的效率,花了一周時間整理了一下68個內置函數,來看看內置函數的騷操作吧!

image

我們先從簡單的開始,再次向大家推薦一下python各種各樣的內置函數,是真的好用,用起來不用自己手寫函數,真的是太爽了,我直呼好家伙。

數學運算

  • abs:對絕對值求和
>>> abs(-2)
2
  • divmod:返回兩個數值的商和余數
>>> divmod(9,4)
(2, 1)
>>> divmod(3.3,2)
(1.0, 1.2999999999999998)
  • max:返回可迭代對象中的元素中的最大值或者所有參數的最大值
>>> max(1,2,3)
3
>>> max('123456')
'6'
>>> max(-1,0)
0
>>> max(-1,0,key=abs) # 傳入了絕對值函數,則所有的參數都會進行絕對值求和再取最大值
-1
  • min:返回可迭代對象中的元素的最小值或者所有參數的最小值

例子max,只是到了過來

  • pow:返回兩個數值的冪運算值或其與指定整數的模值
>>> pow(2,3)
8
>>> 2**3
8
>>> pow(2,3,5)
3
>>> pow(2,3)%5
3
  • round:對浮點數進行四舍五入求值
>>> round(1.3149, 1)
1.3
>>> round(1.13952456,3)
1.14
  • sum:對元素類型是數值的可迭代對象中的每個元素求和
>>> sum((1,2,3,4))
10

類型轉換:類型轉換中,我來介紹幾個我們常用的

  • tuple:根據傳入的參數創建一個新的元組
>>> tuple() #不傳入參數,創建空元組
()
>>> tuple('121') #傳入可迭代對象。使用其元素創建新的元組
('1', '2', '1')
  • list:根據傳入的參數創建一個新的列表
>>>list() # 不傳入參數,創建空列表
[] 
>>> list('abcd') # 傳入可迭代對象,使用其元素創建新的列表
['a', 'b', 'c', 'd']
  • dict:根據傳入的參數創建一個新的字典
>>> dict() # 不傳入任何參數時,返回空字典。
{}
>>> dict(a = 1,b = 2) #  可以傳入鍵值對創建字典。
{'b': 2, 'a': 1}
>>> dict(zip(['a','b'],[1,2])) # 可以傳入映射函數創建字典。
{'b': 2, 'a': 1}
>>> dict((('a',1),('b',2))) # 可以傳入可迭代對象創建字典。
{'b': 2, 'a': 1}
  • set:根據傳入的參數創建一個新的集合
>>>set() # 不傳入參數,創建空集合
set()
>>> a = set(range(10)) # 傳入可迭代對象,創建集合
>>> a
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
  • frozenset:根據 傳入的參數創建一個新的不可變集合
>>> a = frozenset(range(10))
>>> a
frozenset({0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
  • enumerate:根據可迭代對象創建枚舉對象
>>> seasons = ['Spring', 'Summer', 'Fall', 'Winter']
>>> list(enumerate(seasons))
[(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
>>> list(enumerate(seasons, start=1)) #指定起始值
[(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
  • range:根據傳入的參數創建一個新的range對象
>>> a = range(10)
>>> b = range(1,10)
>>> c = range(1,10,3)
>>> a,b,c # 分別輸出a,b,c
(range(0, 10), range(1, 10), range(1, 10, 3))
>>> list(a),list(b),list(c) # 分別輸出a,b,c的元素
([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 4, 7])

  • iter:根據傳入的參數創建一個新的可迭代對象
>>> a = iter('abcd') #字符串序列
>>> a
<str_iterator object at 0x03FB4FB0>
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    next(a)
StopIteration
  • super:根據傳入的參數創建一個新的自雷和父類關系的代理對象(繼承,多態常有

序列操作

  • all:判斷可迭代對象的每個元素是否都為True值
>>> all([1,2]) #列表中每個元素邏輯值均為True,返回True
True
>>> all([0,1,2]) #列表中0的邏輯值為False,返回False
False
>>> all(()) #空元組
True
>>> all({}) #空字典
True
  • any:判斷可迭代對象的元素是否有為rue值得元素
>>> any([0,1,2]) #列表元素有一個為True,則返回True
True
>>> any([0,0]) #列表元素全部為False,則返回False
False
>>> any([]) #空列表
False
>>> any({}) #空字典
False
  • filter:使用指定方法過濾可迭代對象的元素
>>> a = list(range(1,10)) #定義序列
>>> a
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> def if_odd(x): #定義奇數判斷函數
    return x%2==1

>>> list(filter(if_odd,a)) #篩選序列中的奇數
[1, 3, 5, 7, 9]
  • map:使用指定的方法區作用傳入的每個可迭代對象的元素,生成新的可迭代對象
>>> a = map(ord,'abcd')
>>> a
<map object at 0x03994E50>
>>> list(a)
[97, 98, 99, 100]
  • next:返回可迭代對象中的下一個元素值
>>> a = iter('abcd')
>>> next(a)
'a'
>>> next(a)
'b'
>>> next(a)
'c'
>>> next(a)
'd'
>>> next(a)
Traceback (most recent call last):
  File "<pyshell#18>", line 1, in <module>
    next(a)
StopIteration

#傳入default參數后,如果可迭代對象還有元素沒有返回,則依次返回其元素值,如果所有元素已經返回,則返回default指定的默認值而不拋出StopIteration 異常
>>> next(a,'e')
'e'
>>> next(a,'e')
'e'
  • reversed:反轉序列生成新的可迭代對象
>>> a = reversed(range(10)) # 傳入range對象
>>> a # 類型變成迭代器
<range_iterator object at 0x035634E8>
>>> list(a)
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
  • sorted:對可迭代對象進行排序,返回一個新的列表
>>> a = ['a','b','d','c','B','A']
>>> a
['a', 'b', 'd', 'c', 'B', 'A']

>>> sorted(a) # 默認按字符ascii碼排序
['A', 'B', 'a', 'b', 'c', 'd']

>>> sorted(a,key = str.lower) # 轉換成小寫后再排序,'a'和'A'值一樣,'b'和'B'值一樣
['a', 'A', 'b', 'B', 'c', 'd']
  • zip:聚合傳入的每個迭代器中相同位置的元素,返回一個新的元組類型迭代器
>>> x = [1,2,3] #長度3
>>> y = [4,5,6,7,8] #長度5
>>> list(zip(x,y)) # 取最小長度3
[(1, 4), (2, 5), (3, 6)]

對象操作(用的少,可在思維導圖中找到用法解說)

反射操作

  • _import_:動態導入模塊
index = __import__('index')
index.sayHello()
  • isinstance:判斷對象是否非類或者類型元組中的任意類元素的實例
>>> isinstance(1,int)
True
>>> isinstance(1,str)
False
>>> isinstance(1,(int,str))
True
  • issubclass:判斷類是否是另一個類或者類型元組中任意類元素的子類
>>> issubclass(bool,int)
True
>>> issubclass(bool,str)
False

>>> issubclass(bool,(str,int))
True
  • hasatr:檢查對象是否含有屬性
#定義類A
>>> class Student:
    def __init__(self,name):
        self.name = name

        
>>> s = Student('Aim')
>>> hasattr(s,'name') #a含有name屬性
True
>>> hasattr(s,'age') #a不含有age屬性
False
  • getattr:獲取對象的屬性值
#定義類Student
>>> class Student:
    def __init__(self,name):
        self.name = name

>>> getattr(s,'name') #存在屬性name
'Aim'

>>> getattr(s,'age',6) #不存在屬性age,但提供了默認值,返回默認值

>>> getattr(s,'age') #不存在屬性age,未提供默認值,調用報錯
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    getattr(s,'age')
AttributeError: 'Stduent' object has no attribute 'age'
  • seattr:設置對象的屬性值
>>> class Student:
    def __init__(self,name):
        self.name = name

        
>>> a = Student('Kim')
>>> a.name
'Kim'
>>> setattr(a,'name','Bob')
>>> a.name
'Bob'
  • delattr:刪除對象的屬性
#定義類A
>>> class A:
    def __init__(self,name):
        self.name = name
    def sayHello(self):
        print('hello',self.name)

#測試屬性和方法
>>> a.name
'小麥'
>>> a.sayHello()
hello 小麥

#刪除屬性
>>> delattr(a,'name')
>>> a.name
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    a.name
AttributeError: 'A' object has no attribute 'name'
  • callable:檢查對象是否可被調用
>>> class B: #定義類B
    def __call__(self):
        print('instances are callable now.')

        
>>> callable(B) #類B是可調用對象
True
>>> b = B() #調用類B
>>> callable(b) #實例b是可調用對象
True
>>> b() #調用實例b成功
instances are callable now.

變量操作

  • globals:返回當前作用域內的全局變量和其值組成的字典
>>> globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'a': [1, 2, 3, 4, 5, 6, 7, 8, 9], 'if_odd': <function if_odd at 0x03544F60>}
  • locals:返回當前作用域內的局部變量和其值組成的字典
>>> def f():
    print('before define a ')
    print(locals()) #作用域內無變量
    a = 1
    print('after define a')
    print(locals()) #作用域內有一個a變量,值為1

    
>>> f
<function f at 0x03D40588>
>>> f()
before define a 
{} 
after define a
{'a': 1}

交互操作

  • print
  • input

閉上眼睛都會用這兩個啦

文件操作

  • open:使用指定的模式和編碼打開文件,返回文件讀寫對象
# t為文本讀寫,b為二進制讀寫
>>> a = open('test.txt','rt')
>>> a.read()
'some text'
>>> a.close()

下面介紹的內置函數對于我們寫程序來說,絕對會是點睛之筆,一個字牛!!

image

編譯執行

  • compile:將字符串編譯為代碼或者AST對象,使之能夠通過exec語句來執行或者eval進行求值
>>> #流程語句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1)
0
1
2
3
4
5
6
7
8
9


>>> #簡單求值表達式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2)
10
  • eval:計算字符串中有效的表達式,并返回結果,將字符串轉成相應的對象(如list、tuple、dict和string之間的轉換),將利用反引號轉換的字符串再反轉回對象實用性非常強
>>> eval('pow(2,2)')# 計算字符串中有效的表達式,
4
>>> eval('2 + 2')
4
>>> eval("n + 4")
85
# 將字符串轉成相應的對象(如list、tuple、dict和string之間的轉換
>>> a = "[[1,2], [3,4], [5,6], [7,8], [9,0]]"
>>> b = eval(a)
>>> b
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 0]]
>>> a = "{1:'xx',2:'yy'}"
>>> c = eval(a)
>>> c
{1: 'xx', 2: 'yy'}
>>> a = "(1,2,3,4)"
>>> d = eval(a)
>>> d
(1, 2, 3, 4)

# 將利用反引號轉換的字符串再反轉回對象
>>> list1 = [1,2,3,4,5]
>>> `list1`
'[1, 2, 3, 4, 5]'
>>> type(`list1`)
<type 'str'>
>>> type(eval(`list1`))
<type 'list'>
>>> a = eval(`list1`)
>>> a
[1, 2, 3, 4, 5]

  • exec:執行動態語句塊
>>> exec('a=1+2') #執行語句
>>> a
3
  • repr:返回一個對象的字符串表現形式
>>> a = 'some text'
>>> str(a)
'some text'
>>> repr(a)
"'some text'"
image

裝飾器

  • property:表示屬性的裝飾器
>>> class C:
    def __init__(self):
        self._name = ''
    @property
    def name(self):
        """i'm the 'name' property."""
        return self._name
    @name.setter
    def name(self,value):
        if value is None:
            raise RuntimeError('name can not be None')
        else:
            self._name = value

            
>>> c = C()

>>> c.name # 訪問屬性
''
>>> c.name = None # 設置屬性時進行驗證
Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    c.name = None
  File "<pyshell#81>", line 11, in name
    raise RuntimeError('name can not be None')
RuntimeError: name can not be None

>>> c.name = 'Kim' # 設置屬性
>>> c.name # 訪問屬性
'Kim'

>>> del c.name # 刪除屬性,不提供deleter則不能刪除
Traceback (most recent call last):
  File "<pyshell#87>", line 1, in <module>
    del c.name
AttributeError: can't delete attribute
>>> c.name
'Kim'
  • classmethod:標示為類方法的裝飾器
>>> class C:
    @classmethod
    def f(cls,arg1):
        print(cls)
        print(arg1)

        
>>> C.f('類對象調用類方法')
<class '__main__.C'>
類對象調用類方法

>>> c = C()
>>> c.f('類實例對象調用類方法')
<class '__main__.C'>
類實例對象調用類方法
  • staticmethod:標示為靜態方法的裝飾器
# 使用裝飾器定義靜態方法
>>> class Student(object):
    def __init__(self,name):
        self.name = name
    @staticmethod
    def sayHello(lang):
        print(lang)
        if lang == 'en':
            print('Welcome!')
        else:
            print('你好!')

            
>>> Student.sayHello('en') #類調用,'en'傳給了lang參數
en
Welcome!

>>> b = Student('Kim')
>>> b.sayHello('zh')  #類實例對象調用,'zh'傳給了lang參數
zh
你好

PythonGuide :「Python學習+面試指南」一份涵蓋大部分Python相關行業的程序員所需要掌握的核心知識。準備Python面試,來看PythonGuide!

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容