python 內建函式簡單總結

scm1911發表於2019-01-13

python 內建函式

id() hash() type() float() int() bin() hex() oct()
bool() list() tuple() dict() set() complex() bytes() bytearray()
input() print() len() isinstance() issubclass() abs() max() min()
round() pow() range() divmod() sum() chr() ord() str()
repr() ascii() sorted() reversed() enumerate() iter() next() zip()

id()

返回物件的唯一標識,Cpython中返回的是物件的記憶體地址

In [1]: id("a")        
Out[1]: 139855651366088
In [5]: b = range(5)   
In [6]: id(b)          
Out[6]: 139855403437920

hash()

返回的是物件的hash值

In [7]: hash('a')                                                           
Out[7]: -1064091420252831392
In [8]: hash(1)                                                             
Out[8]: 1
In [9]: hash(2000)                                                          
Out[9]: 2000
In [10]: hash(range(5))                                                     
Out[10]: 7573308626029640035
In [11]: hash([1,2])                                                        
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-9ce67481a686> in <module>
----> 1 hash([1,2])

TypeError: unhashable type: 'list'

In [12]: hash({1,2})                                                        
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-d49f6de35e1d> in <module>
----> 1 hash({1,2})

TypeError: unhashable type: 'set'

In [13]: hash({"a":1,"b":2})                                                
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-13-252784143f1f> in <module>
----> 1 hash({"a":1,"b":2})


type()

返回的是物件的型別

In [14]: type(1)            
Out[14]: int
In [15]: type("a")          
Out[15]: str
In [16]: type([1,2])        
Out[16]: list
In [17]: type({1,2})        
Out[17]: set
In [18]: type({"a":1,"b":2})
Out[18]: dict
In [19]: type(range(5))     
Out[19]: range


folat()

轉換浮點型

In [30]: float(10)
Out[30]: 10.0


int()

轉換為整型(只取整數部分)

In [32]: int(10.12141) 
Out[32]: 10
In [33]: int(10.92141) 
Out[33]: 10


bin()

轉換為二進位制

In [34]: bin(7) 
Out[34]: '0b111'


hex()

轉換為十六進位制

In [35]: hex(16) 
Out[35]: '0x10'
In [36]: hex(15) 
Out[36]: '0xf'


oct()

轉換為8進位制

In [38]: oct(8)  
Out[38]: '0o10'
In [39]: oct(7)  
Out[39]: '0o7'
In [40]: oct(9)  
Out[40]: '0o11'
In [41]: oct(16) 
Out[41]: '0o20'
In [42]: oct(32) 
Out[42]: '0o40'


bool()

轉換為布林型

In [43]: bool("a") 
Out[43]: True
In [44]: bool(2)   
Out[44]: True
In [45]: bool(1)   
Out[45]: True
In [46]: bool(0)   
Out[46]: False
In [47]: bool(None)
Out[47]: False
In [48]: bool('')  
Out[48]: False
In [49]: bool(-1)  
Out[49]: True


list()

轉換為列表(需要是可迭代物件)

In [50]: list(range(5)) 
Out[50]: [0, 1, 2, 3, 4]
In [51]: list((1,2,3,4))
Out[51]: [1, 2, 3, 4]


tuple()

轉換為元組
tuple(iterable) -> tuple initialized from iterable's items
If the argument is a tuple, the return value is the same object.

In [53]: tuple([1,2,3,4])
Out[53]: (1, 2, 3, 4)
In [55]: tuple((1,2,3,4)) 
Out[55]: (1, 2, 3, 4)


dict()

轉換為字典
dict() -> new empty dictionary
dict(mapping) -> new dictionary initialized from a mapping object's
(key, value) pairs
dict(iterable) -> new dictionary initialized as if via:
d = {}
for k, v in iterable:
d[k] = v
dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2) back to top

定義一個空字典
d = dict() 或者 d = {}
使用 name=value 對兒初始化一個字典
scm = dict(a=1,b=2)
使用**可迭代物件**和**name=value對**構造字典,不過可迭代物件的元素必須是一個**二元結構**
dict(iterable,\*\*kwarg)
scm = dict((("a",3),("b",4)))
scm = dict([("a",5),("b",6)])
scm = dict({["a",7],["b",8]})    # 錯誤,set中不能有不可hash的物件,[]不可hash
scm = dict([("a",33),("b",44)],x = 00, y = 11)
scm = dict([["a",55],["b",66]],x = 22, y = 33)
scm = dict(((["a"],3),("b",4)))  # 錯誤,key中不能有不可hash的物件
使用mapping 構造字典
dict(mapping,\*\*kwarg)
scm = dict(scm2)   # 使用字典scm2構建字典scm
In [74]: a = dict(enumerate(range(5)))  
In [75]: a                              
Out[75]: {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}
直接使用鍵值對建立字典
scm = {"a":1,"b":"test","c":None,"d":[1,2,3],"e":{1,2,3},"f":{"a":1,1:"new"}}
通過類方法構建字典 **dict.fromkeys(iterable,value)** dict.fromkeys(iterable,value),value是設定的預設值,不指定就是None
scm = dict.fromkeys(range(5))  <==>  scm = dict.fromkeys(range(5),None)
scm = dict.fromkeys(range(5),0)
scm = dict.fromkeys(range(5),"test")

演示

In [1]: scm = dict(a=1,b=2)  
In [2]: scm                  
Out[2]: {'a': 1, 'b': 2}
==============================================================
In [7]: scm = dict((("a",3),("b",4)))                                     
In [8]: scm                                                               
Out[8]: {'a': 3, 'b': 4}
==============================================================
In [9]: scm = dict([("a",5),("b",6)])                                     
In [10]: scm                                                              
Out[10]: {'a': 5, 'b': 6}
==============================================================
In [11]: scm = dict({["a",7],["b",8]})                                    
#--------------------------------------------------------------------------
TypeError                                Traceback (most recent call last)
<ipython-input-11-308a59daea34> in <module>
----> 1 scm = dict({["a",7],["b",8]})
TypeError: unhashable type: 'list'
==============================================================                                                                
In [12]: scm = dict([("a",33),("b",44)],x = 00, y = 11)                   
In [13]: scm                                                              
Out[13]: {'a': 33, 'b': 44, 'x': 0, 'y': 11}
==============================================================
In [14]: scm = dict([["a",55],["b",66]],x = 22, y = 33)                   
In [15]: scm                                                              
Out[15]: {'a': 55, 'b': 66, 'x': 22, 'y': 33}
==============================================================                                                               
In [17]: scm = dict(((["a"],3),("b",4)))                                  
#--------------------------------------------------------------------------
TypeError                                Traceback (most recent call last)
<ipython-input-17-6a1a945e115a> in <module>
----> 1 scm = dict(((["a"],3),("b",4)))
TypeError: unhashable type: 'list'
==============================================================   
In [11]: scm                                                              
Out[11]: {'a': 55, 'b': 66, 'x': 22, 'y': 33}
In [12]: scm2 = dict(scm)                                                 
In [13]: scm2                                                             
Out[13]: {'a': 55, 'b': 66, 'x': 22, 'y': 33}
==============================================================   
In [14]: scm = {"a":1,"b":"test","c":None,"d":[1,2,3],"e":{1,2,3},"f":{"a":1,1:"new"}}                                                   
In [15]: scm                                                                                                                             
Out[15]: 
{'a': 1,
 'b': 'test',
 'c': None,
 'd': [1, 2, 3],
 'e': {1, 2, 3},
 'f': {'a': 1, 1: 'new'}}
==============================================================   
In [16]: scm = dict.fromkeys(range(5)) 
In [17]: scm   
Out[17]: {0: None, 1: None, 2: None, 3: None, 4: None}

In [18]: scm = dict.fromkeys(range(5),0)
In [19]: scm                            
Out[19]: {0: 0, 1: 0, 2: 0, 3: 0, 4: 0}

In [20]: scm = dict.fromkeys(range(5),"test")
In [21]: scm                                                    
Out[21]: {0: 'test', 1: 'test', 2: 'test', 3: 'test', 4: 'test'}

In [22]: scm = dict.fromkeys(range(5),None)            
In [23]: scm                                           
Out[23]: {0: None, 1: None, 2: None, 3: None, 4: None}


set()

轉換為集合
set() -> new empty set object
set(iterable) -> new set object

In [77]: set([1,2,3,4])  
Out[77]: {1, 2, 3, 4}
In [78]: set(range(5))   
Out[78]: {0, 1, 2, 3, 4}


complex()

轉換為複數

In [81]: complex(1)    
Out[81]: (1+0j)
In [82]: complex(-1)   
Out[82]: (-1+0j)
In [83]: complex(-1,2) 
Out[83]: (-1+2j)


bytes()

轉換為位元組 back to top

In [85]: bytes(range(97,123))         
Out[85]: b'abcdefghijklmnopqrstuvwxyz'
In [86]: bytes([97,98,99])            
Out[86]: b'abc'
In [87]: bytes({97,98,99})   
In [89]: bytes(b"abc")         
Out[89]: b'abc'
In [90]: bytes("abc".encode()) 
In [91]: bytes() 
Out[91]: b''


bytearray()

轉換為bytearray

In [93]: bytearray(range(97,123))                
Out[93]: bytearray(b'abcdefghijklmnopqrstuvwxyz')
In [94]: bytearray([97,98,99])                   
Out[94]: bytearray(b'abc')
In [95]: bytearray({97,98,99})                   
Out[95]: bytearray(b'abc')
In [96]: bytearray(b"abc")                       
Out[96]: bytearray(b'abc')
In [97]: bytearray("abc".encode())               
Out[97]: bytearray(b'abc')


input()

接收使用者輸入,返回一個字串

In [100]: input()      
123
Out[100]: '123'
In [101]: input(">>>") 
>>123
Out[101]: '123'


print()

列印輸出,可以指定分隔符和換行符,預設是以空格分隔,換行結尾,輸出到控制檯,返回值是 None.

In [102]: print(123)   
123
In [103]: print("123") 
123
In [106]: print("123","456",sep=" ")
123 456
## 這裡有換行
In [109]: print("123","456",sep=" ",end="")
123 456   # 這裡咩有換行
In [110]:                                  


len()

求物件的長度,物件是一個容器,不能是生成器迭代器

In [110]: len(range(5))                                                     
Out[110]: 5

In [111]: len(( i for i in range(5)))                                       
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-111-b60955f7c630> in <module>
----> 1 len(( i for i in range(5)))

TypeError: object of type 'generator' has no len()

In [112]: len([ i for i in range(5)])                                       
Out[112]: 5

In [113]: iter([1,2,3])                                                    
Out[113]: <list_iterator at 0x7f329f280c50>

In [114]: len(iter([1,2,3]))                                               
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-114-f71e648375a5> in <module>
----> 1 len(iter([1,2,3]))

TypeError: object of type 'list_iterator' has no len()


isinstance(obj,class_or_tuple)

判斷物件obj是否屬於某種型別或者元組中列出的某個型別

isinstace(cls,class_or_tuple)
In [115]: isinstance(1, int)                  
Out[115]: True

In [116]: isinstance(1, (int,str,list))       
Out[116]: True

In [117]: isinstance([1,2,3], (int,str,list)) 
Out[117]: True

In [118]: isinstance({1,2,3}, (int,str,list)) 
Out[118]: False

In [119]: isinstance({1,2,3}, (int,set))      
Out[119]: True


issubclass()

判斷型別cls是否是某種型別的子類或元組中列出的某個型別的子類

issubclass(bool,int)
issubclass(bool,(int,str,float,bool))

In [122]: issubclass(bool,int)                  
Out[122]: True

In [123]: issubclass(bool,(int,str,float,bool)) 
Out[123]: True


abs()

絕對值

In [124]: abs(1)             
Out[124]: 1

In [125]: abs(-1)            
Out[125]: 1

In [126]: abs(-1 +1j)        
Out[126]: 1.4142135623730951

In [127]: abs(-1 -1j)        
Out[127]: 1.4142135623730951


max()

返回可迭代物件中最大

In [130]: max([1,2,3,4])  
Out[130]: 4

In [131]: max(range(5))   
Out[131]: 4

In [132]: max(1,2,3)      


min()

返回可迭代物件中最小值

In [133]: min([1,2,3,4]) 
Out[133]: 1

In [134]: min(range(5))  
Out[134]: 0

In [135]: min(1,2,3)     
Out[135]: 1


round()

round(number[, ndigits]) -> number
取整,原則是四捨六入五取偶

round(3.1234,2)

In [1]: round(3.1234,2) # ndigits 是指定精度
Out[1]: 3.12
In [136]: round(3.5)    
Out[136]: 4
In [137]: round(2.5)    
Out[137]: 2
In [138]: round(2.50001)


pow(x,y)

冪運算
Equivalent to xy (with two arguments) or xy % z (with three arguments)

In [140]: pow(2,3)  
Out[140]: 8
In [141]: pow(2,-3) 
Out[141]: 0.125


range()

從0開始到stop-1的可迭代物件;
range(start, stop[, step])從start開始到stop-1結束步長為step的可迭代物件

In [145]: [ i for i in range(10)]         
Out[145]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [146]: [ i for i in range(5,10)]       
Out[146]: [5, 6, 7, 8, 9]

In [147]: [ i for i in range(5,10,2)]     
Out[147]: [5, 7, 9]

In [148]: [ i for i in range(5,10,-1)]    
Out[148]: []

In [149]: [ i for i in range(5,1,-1)]     
Out[149]: [5, 4, 3, 2]


divmod()

連整除帶取模
等價於tuple (x//y, x%y)

In [150]: divmod(2,3)  
Out[150]: (0, 2)


sum(iterable[, start])

對可迭代物件的所有元素求和

sum(range(1,20,2))
=====================
In [151]: sum(range(1,20,2))
Out[151]: 100
In [152]: sum(range(10))     
Out[152]: 45
In [153]: sum(range(10),100) 
Out[153]: 145


chr(i)

給一個一定範圍的整數返回對應的字元

chr(97)
chr(20013)
=====================
In [154]: chr(97)    
Out[154]: 'a'

In [155]: chr(20013) 
Out[155]: '中'


ord()

返回字元對應的整數

ord('a')
ord('中')
=====================
In [156]: ord('a')   
Out[156]: 97

In [157]: ord('中')  
Out[157]: 20013


str()

待續

repr()

待續

ascii()

待續

sorted(iterable[,key][,reverse])

Signature: sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.

  • 返回的是一個新的列表,預設是升序的
  • key = str 是將元素按照string型別進行排序
  • reverse = True 是反轉
  • iterable 如果是字典就只對鍵排序,返回所以鍵的列表
sorted((1,2,3,4,5,"a","b"), key=str, reverse=True)
=============
In [2]: sorted((1,2,3,4,5,"a","b"), key=str, reverse=True) 
Out[2]: ['b', 'a', 5, 4, 3, 2, 1]


reversed(seq)

翻轉,返回一個翻轉元素的迭代器
不會就地修改。而是倒著去取元素,只能對線性結構的資料進行反轉

list(reversed("13579"))
{ reversed((2, 4)) } # 有幾個元素?只有一個元素: {<reversed at 0x7fcab92c1cf8>}
for x in reversed(['c','b','a']):
print(x)
reversed(sorted({1, 5, 9}))
In [4]: reversed(sorted({1, 5, 9}))              
Out[4]: <list_reverseiterator at 0x7fcab92c1978>
In [1]: for i in reversed(sorted({1, 5, 9})) :
   ...:     print(i)                                       
9
5
1


enumerate(seq,start=0)

列舉,迭代一個序列,返回索引數字和元素構成的二元組,
start表示索引開始的數字,預設是0

In [10]: for i in enumerate(range(4)): 
    ...:     print(i) 
    ...:                                
(0, 0)
(1, 1)
(2, 2)
(3, 3)

In [11]: for i in enumerate("abcdefg"): 
    ...:     print(i,end=' ') 
    ...:                                                       
(0, 'a') (1, 'b') (2, 'c') (3, 'd') (4, 'e') (5, 'f') (6, 'g') 

iter(iterable)

iter將一個可迭代物件封裝成一個迭代器

In [160]: iter([1,2,3,4])                   
Out[160]: <list_iterator at 0x7f329dde7780>                                

In [161]: a = iter([1,2,3,4])               

In [162]: for i in a: 
     ...:     print(i) 
     ...:                                   
1
2
3
4


next()

取元素,next對一個迭代器取下一個元素。如果全部元素都取過了,再次next會拋StopIteration異常
判斷一個物件是不是一個迭代器,通過next()就可以測試出來

range物件雖然是一個可迭代物件,但並不是一個迭代器

In [12]: a = range(5)   
In [13]: next(a)   
-----------------------------------------------------------------
TypeError              Traceback (most recent call last)
<ipython-input-13-15841f3f11d4> in <module>
----> 1 next(a)

TypeError: 'range' object is not an iterator

reversed()函式返回的就是一個迭代器

In [14]: a = reversed(range(5))                      
In [15]: next(a)  
Out[15]: 4
In [16]: next(a)    
Out[16]: 3
In [17]: next(a)     
Out[17]: 2
In [18]: next(a)    
Out[18]: 1
In [19]: next(a)  
Out[19]: 0
In [20]: next(a)                                                            
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-20-15841f3f11d4> in <module>
----> 1 next(a)
StopIteration: 


zip(iterables)

zip我們習慣稱之為拉鍊函式,像拉鍊一樣將多個可迭代物件合併在一起,返回一個迭代器
將每次從不同的物件中取到的元素合併成一個元組
需要注意的是,拉鍊函式的木桶效應,也就是當其中任意一個可迭代物件中的元素取完之後,就不再返回元組了

In [2]: zip(range(5),range(5))                   
Out[2]: <zip at 0x7fcaf450bd48>

In [3]: a = zip(range(5),range(5))               

In [4]: type(a)                                  
Out[4]: zip

In [5]: next(a)                                  
Out[5]: (0, 0)

In [6]: list(zip(range(5),range(5)))             
Out[6]: [(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]                                        

In [7]: list(zip(range(5),range(3)))             
Out[7]: [(0, 0), (1, 1), (2, 2)]

In [8]: list(zip(range(5),range(3),range(2)))    
Out[8]: [(0, 0, 0), (1, 1, 1)]

In [9]: dict(zip(range(5),range(5)))                   
Out[9]: {0: 0, 1: 1, 2: 2, 3: 3, 4: 4}

In [10]: {str(x):y for x,y in zip(range(5),range(5)) } 
Out[10]: {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4}

In [1]: {str(x):y for x,y in zip(["a","b","c","d","e"],range(5)) }  
Out[1]: {'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4}

利用zip函式反轉矩陣

In [2]: list(zip([1,2,3],[4,5,6],[7,8,9])) 
Out[2]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

In [3]: list(zip([1,2],[3,4],[5,6],[7,8])) 
Out[3]: [(1, 3, 5, 7), (2, 4, 6, 8)]


本文連結:https://www.cnblogs.com/shichangming/p/10264132.html

相關文章