Python中的內建函數(Built_in Funtions)


前言

在Python官方文檔的標准庫章節中,第一節是簡介,第二節就是Built_in Functions,可見內建函數是Python標准庫的重要組成部分,而有很多內建函數我們平時卻很少用到或根本就不知道原來還有這么好用的函數居然直接就可以拿來用。

Built_in Funtions

接下來為大家介紹一些我認為被大家忽略掉的內建函數。

all

如果列表或迭代器中所有值都為真或為空返回True,相當於

def all(iterable):    for element in iterable:
       if not element:      
            return False    return True

any

如果迭代器中至少有一個值為真返回True,若迭代器為空返回False,相當於

def any(iterable):    for element in iterable:
       if element:      
           return True    return False

dir

沒有參數時返回當前作用域的所有名稱,有參數時返回該參數的所有屬性

>>> dir(int) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

divmod

同時返回整數除法的商和余數

>>> divmod(11,3)       (3, 2)                 

enumerate

同時返回迭代器元素的索引和值,索引的初始值可以設置,在需要知道元素位置的for循環中很好用

>>> for index, value in enumerate('ABCDEFG'):
...    print(index, value) ...
0 A
1 B
2 C
3 D
4 E
5 F
6 G

id

對於CPython來說就是對象的內存位置

>>> x, y = 1, 2
>>> id(x), id(y) (1666253264, 1666253296)

isinstance

判斷第一個參數是否是第二個參數的實例,以后不要用type(1) == int

>>> isinstance('A',str)
True

結語

希望大家在日后的開發中合理的使用好這些內建函數。

 

原文地址:https://segmentfault.com/a/1190000008604077


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM