python的内置函数 剖析
Posted 仙寓游子
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python的内置函数 剖析相关的知识,希望对你有一定的参考价值。
内置方法:
1. abs() #取绝对值;
>>> abs(-11)
11
>>> abs(11)
11
2. all #非0即真,确保所有元素为真才为真;
>>> all([0, -5, 3])
False
>>> all([1, -5, 3])
True
3. any #非0即真,确保一个元素为真就为真;
>>> any([0, -5, 3])
True
>>> any([1, -5, 3])
True
>>> any([0,0])
False
4. ascii() #将内存对象转变为一个可打印的字符形式
>>> ascii("abcd")
"‘abcd‘"
>>> ascii("abcd111")
"‘abcd111‘"
>>> ascii(1)
‘1‘
>>> ascii([1,2])
‘[1, 2]‘
5. bin() #将十进制数字转换二进制
>>> bin(8)
‘0b1000‘
>>> bin(19)
‘0b10011‘
>>>
6. bool(): #判断是否真,空列表等都为假false
>>> bool([])
False
>>> bool([1,2])
True
>>>
7. bytearray() #把字符变成asscii可以更改;
>>> b = bytearray("abdcd", encoding="utf-8")
>>>
>>> print(b[0])
97
>>> print(b[1])
98
>>> b[1]=100
>>> print(b)
bytearray(b‘addcd‘)
a = bytes("abdcd")
>>> a
b‘abdcd
8. chr() #将ascii值转为对应的字符。
>>> chr(90)
‘Z‘
9. ord() #将字符转为ascii
>>> ord("a")
97
>>> ord("Z")
90
10. complie() #简单的编译反执行。 可以用 exec可以执行字符串源码;
>>> code = "for i in range(10):print(i)"
>>> code
‘for i in range(10):print(i)‘
>>>
>>> compile(code,"","exec")
<code object <module> at 0x00B540D0, file "", line 1>
>>>
>>> c = compile(code,"","exec")
>>> exec(c)
0
1
2
3
4
5
6
7
8
9
>>>
11. dir() #查看对象的方法:
>>> dir({})
[‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘clear‘, ‘copy‘, ‘fromkeys‘, ‘get‘, ‘items‘, ‘keys‘, ‘pop‘, ‘popitem‘, ‘setdefault‘, ‘update‘, ‘values‘]
>>> dir([])
[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__iadd__‘, ‘__imul__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__reversed__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘append‘, ‘clear‘, ‘copy‘, ‘count‘, ‘extend‘, ‘index‘, ‘insert‘, ‘pop‘, ‘remove‘, ‘reverse‘, ‘sort‘]
>>>
12. divmod() #返回商和余数
>>> divmod(5,1)
(5, 0)
>>> divmod(5,2)
(2, 1)
>>> divmod(5,3)
(1, 2)
>>>
13. enumerate(): #
>>> sersons = ["Spring","Summer","Autron","Wintor"]
>>>
>>> list(enumerate(sersons))
[(0, ‘Spring‘), (1, ‘Summer‘), (2, ‘Autron‘), (3, ‘Wintor‘)]
>>>
>>> list(enumerate(sersons, start=1))
[(1, ‘Spring‘), (2, ‘Summer‘), (3, ‘Autron‘), (4, ‘Wintor‘)]
>>>
>>>
>>> for k,v in enumerate(sersons, start=1):print("%d--%s"% (k, v))
...
1--Spring
2--Summer
3--Autron
4--Wintor
>>>
14. eval() #将字符串转为数据类型,不能有语句的,有语句的用exec
>>> x = "[1,2,3,4]"
>>> x
‘[1,2,3,4]‘
>>>
>>> x[0]
‘[‘
>>>
>>> y = eval(x)
>>> y
[1, 2, 3, 4]
>>> y[0]
1
>>>
15. exec() # 执行字符串源码
>>> x = "for i in range(10):print(i)"
>>> x
‘for i in range(10):print(i)‘
>>>
>>>
>>> exec(x)
0
1
2
3
4
5
6
7
8
9
>>>
16. filter(): #按条件进行过滤
>>> x = filter(lambda n:n>5, range(10))
>>> for i in x:print(i)
...
6
7
8
9
将后面的值拿出来给前面处理
>>> x = map(lambda n:n*n, range(10)) #按照范围的输出, 相当于:x = [lambda n:n*n for i in range(10)]
>>> for i in x:print(i)
...
0
1
4
9
16
25
36
49
64
81
匿名函数:只能处理3月运算
>>> lambda n:print(n)
<function <lambda> at 0x0368BDB0>
>>>
>>> (lambda n:print(n))(5)
5
>>>
>>> x=lambda n:print(n)
>>> x(5)
5
>>> lambda m:m*2
<function <lambda> at 0x03716198>
>>> y=lambda m:m*2
>>> y(5)
10
>>>
>>> z = lambda n:3 if n<4 else n
>>> z(2)
3
>>> z(5)
5
17. frozenset() #集合冻结,后即不可修改
>>> a=set([12,2,12,12,12,12])
>>> a
{2, 12}
>>> a.add(13)
>>> a
{2, 12, 13}
>>>
>>> b = frozenset(a)
>>> b
frozenset({2, 12, 13})
>>>
>>>
>>> b.add(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: ‘frozenset‘ object has no attribute ‘add‘
>>>
18. globals() #返回整个程序所有的全局变量值:
>>> globals()
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <class ‘_frozen_importlib.BuiltinImporter‘>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘Iterable‘: <class ‘collections.abc.Iterable‘>, ‘Iterator‘: <class ‘collections.abc.Iterator‘>, ‘x‘: <map object at 0x00B56030>, ‘a‘: {2, 12, 13}, ‘b‘: frozenset({2, 12, 13}), ‘code‘: ‘for i in range(10):print(i)‘, ‘c‘: <code object <module> at 0x00B54128, file "", line 1>, ‘i‘: 81, ‘sersons‘: [‘Spring‘, ‘Summer‘, ‘Autron‘, ‘Wintor‘], ‘k‘: 4, ‘v‘: ‘Wintor‘, ‘y‘: <function <lambda> at 0x036AB6A8>, ‘z‘: <function <lambda> at 0x03716150>}
>>>
19. hash() # 返回hash值;
>>> hash("1")
-585053941
>>>
>>> hash("qwqw")
1784621666
>>>
19. hex() #抓16进制
>>> hex(100)
‘0x64‘
>>> hex(15)
‘0xf‘
>>>
20. oct() #转为8进制
>>> oct(10)
‘0o12‘
21. locals() #打印本地变量;
>>> locals()
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <class ‘_frozen_importlib.BuiltinImporter‘>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘Iterable‘: <class ‘collections.abc.Iterable‘>, ‘Iterator‘: <class ‘collections.abc.Iterator‘>, ‘x‘: <map object at 0x00B56030>, ‘a‘: {2, 12, 13}, ‘b‘: frozenset({2, 12, 13}), ‘code‘: ‘for i in range(10):print(i)‘, ‘c‘: <code object <module> at 0x00B54128, file "", line 1>, ‘i‘: 81, ‘sersons‘: [‘Spring‘, ‘Summer‘, ‘Autron‘, ‘Wintor‘], ‘k‘: 4, ‘v‘: ‘Wintor‘, ‘y‘: <function <lambda> at 0x036AB6A8>, ‘z‘: <function <lambda> at 0x03716150>}
>>>
21. max(): #返回最大值
>>> max([1,2,3,4,5])
5
1. abs() #取绝对值;
>>> abs(-11)
11
>>> abs(11)
11
2. all #非0即真,确保所有元素为真才为真;
>>> all([0, -5, 3])
False
>>> all([1, -5, 3])
True
3. any #非0即真,确保一个元素为真就为真;
>>> any([0, -5, 3])
True
>>> any([1, -5, 3])
True
>>> any([0,0])
False
4. ascii() #将内存对象转变为一个可打印的字符形式
>>> ascii("abcd")
"‘abcd‘"
>>> ascii("abcd111")
"‘abcd111‘"
>>> ascii(1)
‘1‘
>>> ascii([1,2])
‘[1, 2]‘
5. bin() #将十进制数字转换二进制
>>> bin(8)
‘0b1000‘
>>> bin(19)
‘0b10011‘
>>>
6. bool(): #判断是否真,空列表等都为假false
>>> bool([])
False
>>> bool([1,2])
True
>>>
7. bytearray() #把字符变成asscii可以更改;
>>> b = bytearray("abdcd", encoding="utf-8")
>>>
>>> print(b[0])
97
>>> print(b[1])
98
>>> b[1]=100
>>> print(b)
bytearray(b‘addcd‘)
a = bytes("abdcd")
>>> a
b‘abdcd
8. chr() #将ascii值转为对应的字符。
>>> chr(90)
‘Z‘
9. ord() #将字符转为ascii
>>> ord("a")
97
>>> ord("Z")
90
10. complie() #简单的编译反执行。 可以用 exec可以执行字符串源码;
>>> code = "for i in range(10):print(i)"
>>> code
‘for i in range(10):print(i)‘
>>>
>>> compile(code,"","exec")
<code object <module> at 0x00B540D0, file "", line 1>
>>>
>>> c = compile(code,"","exec")
>>> exec(c)
0
1
2
3
4
5
6
7
8
9
>>>
11. dir() #查看对象的方法:
>>> dir({})
[‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘clear‘, ‘copy‘, ‘fromkeys‘, ‘get‘, ‘items‘, ‘keys‘, ‘pop‘, ‘popitem‘, ‘setdefault‘, ‘update‘, ‘values‘]
>>> dir([])
[‘__add__‘, ‘__class__‘, ‘__contains__‘, ‘__delattr__‘, ‘__delitem__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, ‘__getattribute__‘, ‘__getitem__‘, ‘__gt__‘, ‘__hash__‘, ‘__iadd__‘, ‘__imul__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__iter__‘, ‘__le__‘, ‘__len__‘, ‘__lt__‘, ‘__mul__‘, ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__reversed__‘, ‘__rmul__‘, ‘__setattr__‘, ‘__setitem__‘, ‘__sizeof__‘, ‘__str__‘, ‘__subclasshook__‘, ‘append‘, ‘clear‘, ‘copy‘, ‘count‘, ‘extend‘, ‘index‘, ‘insert‘, ‘pop‘, ‘remove‘, ‘reverse‘, ‘sort‘]
>>>
12. divmod() #返回商和余数
>>> divmod(5,1)
(5, 0)
>>> divmod(5,2)
(2, 1)
>>> divmod(5,3)
(1, 2)
>>>
13. enumerate(): #
>>> sersons = ["Spring","Summer","Autron","Wintor"]
>>>
>>> list(enumerate(sersons))
[(0, ‘Spring‘), (1, ‘Summer‘), (2, ‘Autron‘), (3, ‘Wintor‘)]
>>>
>>> list(enumerate(sersons, start=1))
[(1, ‘Spring‘), (2, ‘Summer‘), (3, ‘Autron‘), (4, ‘Wintor‘)]
>>>
>>>
>>> for k,v in enumerate(sersons, start=1):print("%d--%s"% (k, v))
...
1--Spring
2--Summer
3--Autron
4--Wintor
>>>
14. eval() #将字符串转为数据类型,不能有语句的,有语句的用exec
>>> x = "[1,2,3,4]"
>>> x
‘[1,2,3,4]‘
>>>
>>> x[0]
‘[‘
>>>
>>> y = eval(x)
>>> y
[1, 2, 3, 4]
>>> y[0]
1
>>>
15. exec() # 执行字符串源码
>>> x = "for i in range(10):print(i)"
>>> x
‘for i in range(10):print(i)‘
>>>
>>>
>>> exec(x)
0
1
2
3
4
5
6
7
8
9
>>>
16. filter(): #按条件进行过滤
>>> x = filter(lambda n:n>5, range(10))
>>> for i in x:print(i)
...
6
7
8
9
将后面的值拿出来给前面处理
>>> x = map(lambda n:n*n, range(10)) #按照范围的输出, 相当于:x = [lambda n:n*n for i in range(10)]
>>> for i in x:print(i)
...
0
1
4
9
16
25
36
49
64
81
匿名函数:只能处理3月运算
>>> lambda n:print(n)
<function <lambda> at 0x0368BDB0>
>>>
>>> (lambda n:print(n))(5)
5
>>>
>>> x=lambda n:print(n)
>>> x(5)
5
>>> lambda m:m*2
<function <lambda> at 0x03716198>
>>> y=lambda m:m*2
>>> y(5)
10
>>>
>>> z = lambda n:3 if n<4 else n
>>> z(2)
3
>>> z(5)
5
17. frozenset() #集合冻结,后即不可修改
>>> a=set([12,2,12,12,12,12])
>>> a
{2, 12}
>>> a.add(13)
>>> a
{2, 12, 13}
>>>
>>> b = frozenset(a)
>>> b
frozenset({2, 12, 13})
>>>
>>>
>>> b.add(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: ‘frozenset‘ object has no attribute ‘add‘
>>>
18. globals() #返回整个程序所有的全局变量值:
>>> globals()
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <class ‘_frozen_importlib.BuiltinImporter‘>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘Iterable‘: <class ‘collections.abc.Iterable‘>, ‘Iterator‘: <class ‘collections.abc.Iterator‘>, ‘x‘: <map object at 0x00B56030>, ‘a‘: {2, 12, 13}, ‘b‘: frozenset({2, 12, 13}), ‘code‘: ‘for i in range(10):print(i)‘, ‘c‘: <code object <module> at 0x00B54128, file "", line 1>, ‘i‘: 81, ‘sersons‘: [‘Spring‘, ‘Summer‘, ‘Autron‘, ‘Wintor‘], ‘k‘: 4, ‘v‘: ‘Wintor‘, ‘y‘: <function <lambda> at 0x036AB6A8>, ‘z‘: <function <lambda> at 0x03716150>}
>>>
19. hash() # 返回hash值;
>>> hash("1")
-585053941
>>>
>>> hash("qwqw")
1784621666
>>>
19. hex() #抓16进制
>>> hex(100)
‘0x64‘
>>> hex(15)
‘0xf‘
>>>
20. oct() #转为8进制
>>> oct(10)
‘0o12‘
21. locals() #打印本地变量;
>>> locals()
{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: <class ‘_frozen_importlib.BuiltinImporter‘>, ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: <module ‘builtins‘ (built-in)>, ‘Iterable‘: <class ‘collections.abc.Iterable‘>, ‘Iterator‘: <class ‘collections.abc.Iterator‘>, ‘x‘: <map object at 0x00B56030>, ‘a‘: {2, 12, 13}, ‘b‘: frozenset({2, 12, 13}), ‘code‘: ‘for i in range(10):print(i)‘, ‘c‘: <code object <module> at 0x00B54128, file "", line 1>, ‘i‘: 81, ‘sersons‘: [‘Spring‘, ‘Summer‘, ‘Autron‘, ‘Wintor‘], ‘k‘: 4, ‘v‘: ‘Wintor‘, ‘y‘: <function <lambda> at 0x036AB6A8>, ‘z‘: <function <lambda> at 0x03716150>}
>>>
21. max(): #返回最大值
>>> max([1,2,3,4,5])
5
23. min(): #返回最小值
>>> min([1,2,3,4,5])
1
24. pow(x,y) #返回多次幂,x的y次方
>>> pow(2,2)
4
>>> pow(2,3)
8
25. range(start,stop,step)
>>> min([1,2,3,4,5])
1
24. pow(x,y) #返回多次幂,x的y次方
>>> pow(2,2)
4
>>> pow(2,3)
8
25. range(start,stop,step)
26. repr() #用字符串表示一个对对象:
27. reversed(seq) #反转
28. round() #浮点数按照规定四舍五入舍弃,
>>> round(1.232442)
1
>>> round(1.232442,2)
1.23
>>> round(1.237442,2)
1.24
>>>
29. id() #取内存id值
>>> id("1")
56589120
>>> id("a")
56501888
30. sorted(iterable[,key][,reverse]) #排序
>>> a = {5:1,9:2,1:3,8:4,3:9}
>>>
>>> sorted(a)
[1, 3, 5, 8, 9]
>>> sorted(a.items())
[(1, 3), (3, 9), (5, 1), (8, 4), (9, 2)]
>>> sorted(a.items(),key=lambda x:x[1])
[(5, 1), (9, 2), (1, 3), (8, 4), (3, 9)]
27. reversed(seq) #反转
28. round() #浮点数按照规定四舍五入舍弃,
>>> round(1.232442)
1
>>> round(1.232442,2)
1.23
>>> round(1.237442,2)
1.24
>>>
29. id() #取内存id值
>>> id("1")
56589120
>>> id("a")
56501888
30. sorted(iterable[,key][,reverse]) #排序
>>> a = {5:1,9:2,1:3,8:4,3:9}
>>>
>>> sorted(a)
[1, 3, 5, 8, 9]
>>> sorted(a.items())
[(1, 3), (3, 9), (5, 1), (8, 4), (9, 2)]
>>> sorted(a.items(),key=lambda x:x[1])
[(5, 1), (9, 2), (1, 3), (8, 4), (3, 9)]
>>> a.items() #将字典转化为列表。
dict_items([(5, 1), (9, 2), (1, 3), (8, 4), (3, 9)])
>>>
>>> list(a)
[5, 9, 1, 8, 3]
31. sum(iterable[,start]) #求和,start为sum初始值
>>> sum([1, 3, 5, 8, 9])
26
>>> sum([1, 3, 5, 8, 9],3)
29
>>> sum([1, 3, 5, 8, 9],30)
56
32. tuple(iterable): #转化为元组
>>> tuple([1, 3, 5, 8, 9])
(1, 3, 5, 8, 9)
34. zip() #中文就是拉链的意思,一一对应
>>> a = (1, 3, 5, 8, 9)
>>> b = ("a","b","c","d","e")
>>>
>>> zip(a,b)
<zip object at 0x00B53990>
>>> for n in zip(a,b):
... print(n)
...
(1, ‘a‘)
(3, ‘b‘)
(5, ‘c‘)
(8, ‘d‘)
(9, ‘e‘)
>>>
35. __import__("模块名") #只知道模块名时导入模块就方法:
以上是关于python的内置函数 剖析的主要内容,如果未能解决你的问题,请参考以下文章