内置函数
内置函数
前面使用过一些函数,有的人会疑问我没有导入这个函数,为什么可以直接使用?
因为这些函数都是一个叫做builtins模块中定义的函数,而builtins模块默认在Python环境启动的时候就自动导入,所以你可以直接使用这些函数。
我们可以在IDLE 进行输出
globals()
{'__name__':'__main__','__doc__':None,'__package__':None,'__loader__'<class'_frozen_importlib.BuiltinImporter'>,'__spec__':None,'__annotations__'{},'__builtins__':<module'builtins'(built-in)>}
dir(__builtins__)
['ArithmeticError','AssertionError','AttributeError','BaseException','BlockingIOError','BrokenPipeError','BufferError','BytesWarning','ChildProcessError','ConnectionAbortedError','ConnectionError','ConnectionRefusedError','ConnectionResetError','DeprecationWarning','EOFError','Ellipsis','EnvironmentError','Exception','False','FileExistsError','FileNotFoundError','FloatingPointError','FutureWarning','GeneratorExit','IOError','ImportError','ImportWarning','IndentationError','IndexError','InterruptedError','IsADirectoryError','KeyError','KeyboardInterrupt','LookupError','MemoryError','ModuleNotFoundError','NameError','None','NotADirectoryError','NotImplemented','NotImplementedError','OSError','OverflowError','PendingDeprecationWarning','PermissionError','ProcessLookupError','RecursionError','ReferenceError','ResourceWarning','RuntimeError','RuntimeWarning','StopAsyncIteration','StopIteration','SyntaxError','SyntaxWarning','SystemError','SystemExit','TabError','TimeoutError','True','TypeError','UnboundLocalError','UnicodeDecodeError','UnicodeEncodeError','UnicodeError','UnicodeTranslateError','UnicodeWarning','UserWarning','ValueError','Warning','WindowsError','ZeroDivisionError','_','__build_class__','__debug__','__doc__','__import__','__loader__','__name__','__package__','__spec__','abs','all','any','ascii','bin','bool','bytearray','bytes','callable','chr','classmethod','compile','complex','copyright','credits','delattr','dict','dir','divmod','enumerate','eval','exec','exit','filter','float','format','frozenset','getattr','globals','hasattr','hash','help','hex','id','input','int','isinstance','issubclass','iter','len','license','list','locals','map','max','memoryview','min','next','object','oct','open','ord','pow','print','property','quit','range','repr','reversed','round','set','setattr','slice','sorted','staticmethod','str','sum','super','tuple','type','vars','zip']
builtins模块里有接近80个内置函数,60多个内置异常,还有几个内置常数,特殊名称以及模块相关的属性。
接下来给大家介绍一些工作中常用的一些内置函数:\
abs()
绝对值函数。如abs(-1)=1
abs(-10)
10
f = abs
f(-1)
1
abs=id
abs(1)
18322788382
以abs()函数为例,展示两个特性。一是,内置函数是可以被赋值给其他变量的,同样也可以将其他对象赋值给内置函数,这时就完全变了。所以,内置函数不是Python关键字,要注意对它们的保护,不要使用和内置函数重名的变量名,这会让代码混乱,容易发生难以排查的错误。
all()
接收一个可迭代对象,如果对象里的所有元素的bool运算值都是True,那么返回True,否则False
all([1,1,1])
True
all([1,1,0])
False
any()
接收一个可迭代对象,如果迭代对象里有一个元素的bool运算值是True,那么返回True,否则False。与all()是一对兄弟。
any([0,0,1])
True
any([0,0,0])
False
bin()、oct()、hex()
三个函数是将十进制数分别转换为2/8/16进制。
i =10
bin(i)
'0b1010' #0b表示2进制
oct(i)
'0o12' #0o表示8进制
hex(i)
'0xa' #0x表示16进制
bool()
测试一个对象或表达式的执行结果是True还是False。
bool(1==2)
False
bool(abs(-1))
True
bool(None)
False
bytes()
将对象转换成字节类型。例如:s =‘张三’;m = bytes (s, encoding=‘utf-8’)
i=2
bytes(i)
b'\x00\x00'
s ='haha'
bytes(s)
Traceback(most recent call last):
File"<pyshell#24>",line 1,in <module>
bytes(s)
TypeError:string argument without an encoding
bytes(s,encoding="utf-8")
b'haha'
bytes(s,encoding="GBK")
b'haha'
s ="python"
s.encode() #将字符串转换成bytes
str()
将对象转换成字符串类型,同样也可以指定编码方式。例如:str(bytes对象,encoding=‘utf-8’)
i =2
str(i)
'2'
b =b"haha"
str(b) #注意!
"b'haha'"
str(b,encoding="gb2312")
'haha'
str([1,2,3,])
'[1,2,3]'
b =b'python'
b.decode() #将bytes转换成str
Bytes和string之间的互相转换,更多使用的是encode()和decode()方法。
chr()
返回某个十进制数对应的ASCII字符,例如:chr(99)=‘c’。 它可以配合random.randint(65,90)随机方法,生成随机字符,用于生产随机验证码。
import random
for i in range(10):
a =random.randint(65,90) #65-90是ASCII表中A-Z
c =chr(a)
print(c,end='')
print('')
ord()
与chr()相反,返回某个ASCII字符对应的十进制数,例如,ord(‘A’)=65
ord("A")
65
ord("\n")
10
compile()
将字符串编译成Python能识别或执行的代码
s ="print('hello world')"
r =compile(s,"<string>","exec")
r
<code object <module> at 0x000001B23E6BE660,file"<string>",line 1>
r()
Traceback(most recent call last):
File"<pyshell#14>",line 1,in <module>
r()
TypeError:'code' object is not callable
exec(r) #执行的话需要用exec
hello world
eval(r) #eval也可以
hello world
complex()
通过数字或字符串生成复数类型对象。
complex(1,2)
(1+2j)
dir()
显示对象所有的属性和方法。
dir([1,2,])
['__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']
divmod()
除法,同时返回商和余数的元组。
divmod(10,3)
(3,1)
divmod(11,4)
(2,3)
format()
执行format(),其实就是调用该对象所属类的__format__方法。
format("200211")
'200211'
format([1,2,3])
'[1,2,3]'
globals()
列出当前环境下所有的全局变量。注意要与global关键字区分!
hash()
为不可变对象,例如字符串生成哈希值的函数!
hash("i am jack")
5602200374213231465
hash(1)
1
hash(100000)
100000
hash([1,2,3,])
Traceback(most recent call last):
File "<pyshell#4>", line 1,in <module>
hash([1,2,3,])
TypeError:unhashable type: 'list'
hash((1,2,3))
2528502973977326415
id()
返回对象的内存地址,常用来查看变量引用的变化,对象是否相同等。常用功能之一!
id(0)
1456845856
id(True)
1456365792
a ="Python"
id(a)
37116704
iter()
制造一个迭代器,使其具备next()能力。
lis =[1,2,3]
next(lis)
Traceback(most recent call last):
File "<pyshell#8>",line 1,in <module>
next(lis)
TypeError:'list' object is not an iterator
i =iter(lis)
i
<list_iterator object at 0x0000000002B4A128>
next(i)
1
len()
返回对象的长度。不能再常用的函数之一了。
max min
返回给定集合里的最大或者最小的元素。可以指定排序的方法!
lis =['abcaaaa','abcd','abcde']
max(lis)
指定按照长度返回
max(lis,key=len)
next()
通过调用迭代器的__next__()方法,获取下一个元素。
open()
打开文件的方法。在Python2里,还有一个file()方法,Python3中被废弃了。
pow()
幂函数。
>>> pow(3,2)
9
reversed()
反转,逆序对象
>>> reversed #reversed本身是个类
<class 'reversed'>
>>> reversed([1,2,3,4,5]) #获得一个列表反转器<list_reverseiterator object at 0x0000022E322B5128>
>>> a =reversed([1,2,3,4,5])
>>> a
<list_reverseiterator object at 0x0000022E32359668>
>>> list(a) #使用list方法将它转换为一个列表
[5,4,3,2,1]
round()
四舍五入.
round(1.5)
2
round(1.4)
1
sum()
求和.
>>> sum(1,2,3) #需要传入一个可迭代的对象Traceback(most recent call last):
File "<pyshell#15>",line 1,in <module>
sum(1,2,3)
TypeError:sum expected at most 2 arguments,got 3
>>> sum([1,2,3]) #传入一个列表
6
>>> sum({1:1,2:2}) #突发奇想,作死传入一个字典
3
type()
显示对象所属的数据类型。常用方法!前面已经展示过。
filter()
过滤器,用法和map类似。在函数中设定过滤的条件,逐一循环对象中的元素,将返回值为True时的元素留下
(注意,不是留下返回值!),形成一个filter类型的迭代器。
def f1(x):
if x > 3:
return True
else:
return False
li =[1,2,3,4,5]
data =filter(f1,li)
print(type(data))
print(list(data))
运行结果:
<class 'filter'>
[4,5]
zip()
组合对象。将对象逐一配对。
list_1 =[1,2,3]
list_2 =['a','b','c']
s =zip(list_1,list_2)
print(list(s))
运行结果:
[(1,'a'),(2,'b'),(3,'c')]
组合3个对象:
list_1 =[1,2,3,4]
list_2 =['a','b','c',"d"]
list_3 =['aa','bb','cc',"dd"]
s =zip(list_1,list_2,list_3)
print(list(s))
运行结果:
[(1,'a','aa'),(2,'b','bb'),(3,'c','cc'),(4,'d','dd')]
那么如果对象的长度不一致呢?多余的会被抛弃!以最短的为基础!
list_1 =[1,2,3]
list_2 =['a','b','c',"d"]
s =zip(list_1,list_2)
print(list(s))
运行结果:
[(1,'a'),(2,'b'),(3,'c')]
sorted()
排序方法。有key和reverse两个重要参数。
基础用法:直接对序列进行排序
>>> sorted([36,5,-12,9,-21])
[-21,-12,5,9,36]
指定排序的关键字。关键字必须是一个可调用的对象。例如下面的例子,规则是谁的绝对值大,谁就排在后面。
>>> sorted([36,5,-12,9,-21],key=abs)
[5,9,-12,-21,36]
指定按反序排列。下面的例子,首先按忽略大小写的字母顺序排序,然后倒序排列。
>>> sorted(['bob','about','Zoo','Credit'],key=str.lower, reverse=True)
['Zoo','Credit','bob','about']