python 内建函数

Posted shichangming

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 内建函数相关的知识,希望对你有一定的参考价值。

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()

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: 


什么是可迭代对象

定义

能够通过迭代一次次返回不同的元素的对象

对可迭代对象的概念上需要注意的几点有:

  • 要注意的是可迭代对象中的相同元素指的是是元素在容器中是否是同一个,而不是指值是否相同。
    如列表中的值就是可以重复的,列表中的不同元素实际上就是索引不同
    ["a","a"]
  • 可迭代对象不一定是线性结构的,也就是不一定有序不一定有所索引,比如 set dict

常见的可迭代对象

list, tuple, string, bytes, bytearray, range, set, dict, 生成器

对可迭代对象的 in 操作

可以使用成员操作符 in , not in, in 和 not in本质上就是在对可迭代对象进行遍历

1 in range(5)
3 in ( i for i in range(5))
3 in { x:y for x,y in zip(range(4),range(4,10)) }
In [21]: 3 in ( i for i in range(5))
Out[21]: True

In [23]: 3 in { x:y for x,y in zip(range(4),range(4,10)) } 
Out[23]: True


什么是迭代器

  • 迭代器是一个特殊的对象,是可迭代对象,具备可迭代对象的特征
  • 通过iter方法可以把一个可迭代对象封装成一个迭代器
  • 通过next方法可以对迭代器进行迭代,但是只能迭代一次
  • 生成器对象是属于迭代器的一种
  • 使用 iter 方法对迭代器封装后还是一个迭代器
In [24]: type(range(5))      
Out[24]: range
In [25]: type(iter(range(5)))
Out[25]: range_iterator

In [27]: for i in iter(range(5)):
    ...:     print(i) 
    ...:                         
0
1
2
3
4
In [28]: g = ( x for x in range(5) )                                        
In [29]: print(type(g))                                                     
<class ‘generator‘>
In [30]: print(next(g))                                                     
0
In [31]: print(next(g))                                                     
1
In [32]: print(next(g))                                                   
2
In [33]: print(next(g))                                                   
3
In [34]: print(next(g))                                                    
4
In [35]: print(next(g))                                                   
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-35-1dfb29d6357e> in <module>
----> 1 print(next(g))

StopIteration: 


本文链接:https://www.cnblogs.com/shichangming/p/10264132.html





























































以上是关于python 内建函数的主要内容,如果未能解决你的问题,请参考以下文章

python 六剑客(匿名函数和内建函数)

Python 字符串 String 内建函数大全

Python 字符串 String 内建函数大全

Python中的内建函数

复习 Python 匿名函数 内建函数

Python中的内建函数