目录
Python解释器提供了68个内置函数,这些函数不需要引用库直接使用,需要熟练掌握常用内置函数。
本篇文章带你一起熟悉Python常用内置函数。
与数值运算有关
abs(x)
x的绝对值
a = -1
print(abs(a))
运行结果:1
divmod(x,y)
(x//y,x%y),输出为二元组形式(也称元组类型) 。
把除数和余数运算结合起来,返回一个包含商和余数的元组。
a = 9
b = 5
print(divmod(a, b))
运行结果:(1,4)
pow(x,y[,z])
(x**y)%z,[...]表示该参数可以省略。计算并返回x的y次方。其中x是底数,y是指数,z是取余数字。
1.当参数z省略时,pow函数返回x的y次方。
print(pow(2, 2))
运行结果:4
2.当参数z存在时,pow(x,y,z)的返回结果就等于pow(x,y)的结果对z求余。
print(pow(2, 2, 3))
运行结果:1
round(x[,ndigits])
对x四舍五入,保留ndigits位小数。
digits>0,四舍五入到指定的小数位
digits=0,四舍五入到最接近的整数
digits<o,在小数点左侧进行四舍五入
print(round(3.1415926, 5))
print(round(3.1415926, 0))
print(round(34.1415926, -1))
print(round(35.1415926, -1))
运行结果:3.14159
3.0
30.0
40.0
max()
求的最大值,n没有限定
print(max(1,2,3,43,5,5454,5454,6,7,90,23333))
运行结果:23333
min()
的最小值,n没有限定
print(min(1,2,3,43,5,5454,5454,6,7,90,23333))
运行结果:1
sum(iterable[,start])
sum()函数对序列进行求和运算。
iterable——可迭代对象,如list,tuple,set,dictionary
start——指定相加的参数,如果没有,默认为0
print(sum([1, 2], 3))
print(sum([1, 2]))
print(sum(range(101)))
运行结果:6
3
5050
oct(x)
oct()函数用于获取给定数字的八进制值,以字符串格式返回。
a = 10
b = oct(a)
print(b)
print(type(a))
print(type(b))
运行结果:0o12
<class 'int'>
<class 'str'>
hex(x)
hex()函数用于获取给定数字的十六进制值,以字符串格式返回。
a = 10
b = hex(a)
print(b)
print(type(a))
print(type(b))
运行结果:0xa
<class 'int'>
<class 'str'>
bin(x)
bin()函数返回一个整数的二进制值,以字符串格式返回。
a = 10
b = bin(a)
print(b)
print(type(a))
print(type(b))
运行结果:0b1010
<class 'int'>
<class 'str'>
与类型转换有关
int(x,base)
将x转换为整数,x可以是浮点数或者字符串,base进制数,默认十进制。
1.当x是纯数字时,base必须省略。
print(int(3.14))
print(int(-3.14))
运行结果:3
-3
2.当x是字符串时,base可以省略。
print(int("7", 8))
print(int("1001", 2))
print(int("0xa", 16))
运行结果:7
9
10
float([x])
float()函数是将一个数字或字符串转换成浮点数,返回一个十进制浮点型数值。
float([x])中x可以是十进制的数,bool类型,十进制数字的字符串。
print(float()) # 如果为给定参数,返回结果为0.0
print(float(10)) # 如果参数为整数,返回结果为等值的浮点数,10.0
print(float(True)) # 如果参数是布尔值True,返回1.0
print(float(False)) #如果参数是布尔值False,返回0.0
print(float('7')) #如果参数是十进制数字的字符串,返回等值的浮点数7.0
str()
str(object)函数将参数转换成字符串类型。
1.当str()参数省略时,函数返回空的字符串。常用来创建空字符串或者初始化字符串变量。
print(str()) # 返回一个空字符串
2.当str()不省略参数时,将整数、浮点数、列表、元组、字典、集合转换成字符串类型。
print(str(10)) # 当参数是整数,返回整数的字符串类型,10
print(type(str(10))) # 'str'类型
print(str(10.0)) # 当参数是浮点数,返回浮点数的字符串类型,10.0
print(type(str(10.0))) # 'str'类型
# 将列表转换为字符串
list_1 = [1, 2, 3, 4, 5]
list_2 = str(list_1)
print(type(list_2))
print(list_2[0]) # 输出为"["
# 将元组转换成字符串
tuple_1 = (1, 2, 3, 4, 5)
tuple_2 = str(tuple_1)
print(type(tuple_2))
print(tuple_2[0]) # 输出为"("
注意:将列表、元组、字典、集合转换成字符串后,包裹他们的'['']''('')''{''}'',还有他们里面元素分隔符和字典中的":" 也都转换成了字符串。
list([iterable])
list()函数可以将任何可迭代数据转换成列表类型,并且返回转换后的列表。
# 当没有参数时,创建一个空的列表
list_1 = list()
print(list_1) # 输入结果是[]
# 将字符串转换成列表
str_1 = 'str'
list_2 = list(str_1)
print(list_2) # 输出结果:['s', 't', 'r']
# 将元组转换成列表
tuple_1 = ('tuple', '可乐不加糖')
list_3 = list(tuple_1)
print(list_3) #输出结果:['tuple', '可乐不加糖']
# 将集合转换成列表
set_1 = {'set', 1, 3}
list_4 = list(set_1)
print(list_4) # 输出结果:['set', 3, 1]
# 将字典转换成列表
dict_1 = {'我是': '汪小康', '我爱': '中国'}
print(dict_1) # 输出结果:{'我是': '汪小康', '我爱': '中国'}
list_5 = list(dict_1)
print(list_5) # 输出结果:['我是', '我爱']
complex(re[,im])
生成一个复数,实部是re,虚部是im,re可以是整数、浮点数、字符串,im可以是整数、浮点数,但不能是字符串。
print(complex(2.99)) # 输出结果:(2.99+0j)
print(complex(2.99, 3)) #输出结果:(2.99+3j)
print(complex("2.99")) #输出结果:(2.99+0j)
print(complex(2.99, 2.99)) # 输出结果:(2.99+2.99j)
注意:当实部是字符串时,不在接受虚部,否则会报错。
TypeError: complex() can't take second arg if first is a string
与序列有关
len()
len()函数返回字符串、列表、元组、字典等的长度。
list1 = [1, 2, 3, 4, 5, 6]
print(len(list1)) #6
tuple1 = (1, 2, 3, 3, 4, 5)
print(len(tuple1)) #6
set1 = ([1, 2, 3, 3, 4, 5])
print(len(set1)) #6
dict1 = {'1': 'q', '2': 'w'}
print(len(dict1)) # 2
all()
all()函数一般针对组合数据类型,如果其中每个元素都是True,返回True。否则返回False。
其中,整数0,空字符串" ",空列表[ ] 等都被当作False.
any()
any()函数与all()函数相反,只要组合数据类型中任意一个是True,就返回True。当全部元素是False,才返回False。
cmp(x, y)
sorted()
sorted()函数对一个序列进行排序。帮助文档:
Help on built-in function sorted in module builtins:
sorted(iterable, /, *, key=None, reverse=False)
Return a new list containing all items from the iterable in ascending order.
A custom key function can be supplied to customize the sort order, and the
reverse flag can be set to request the result in descending order.
sorted()一共有三个参数,key和reverse是可选的。iterable是可迭代对象,key是排序的依据,reverse是升序还是降序,默认升序。
list1 = [2, 3, 1, 7, 0]
print(sorted(list1)) #输出结果:[0, 1, 2, 3, 7]
# 默认是升序排序,当需要降序排序时,reverse = True
print(sorted(list1, reverse=True)) # 输出结果:[7, 3, 2, 1, 0]
# key用来接收一个自定义的排序规则
list2 = [0, 4, 6, -1, -3]
print(sorted(list2)) # [-3, -1, 0, 4, 6]
print(sorted(list2, key=abs)) # [0, -1, -3, 4, 6]
reversed()
与对象操作有关
help([object])
简单来说,help()函数就是用于获取指定模块、类、函数、变量等的文档。此方法通常与python解释器控制台一起使用,来获取有关python对象的详细信息。
1.当未提供参数时,则交互式帮助系统将在解释器控制台启动。
# 未提供参数
help()
在python帮助控制台中,我们可以指定模块、类、方法名称来获取其帮助文档。下面是获取到的print函数的帮助文档。如果想要退出帮助控制台,输入quit即可。
help> print
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
help>
2.通过将参数传递给help()函数,我们可以直接从控制台获取帮助文档。
help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
id([object])
Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.
CPython implementation detail: This is the address of the object in memory.
返回一个对象的“标识符”。这是一个整数,保证该对象在其生命周期内是唯一和恒定的。两个生命周期不重叠的对象可能具有相同的id()值。CPython实现细节:这是内存中对象的地址。
简单来说,id()函数就是用于获取对象的内存地址。
a = 9
print(id(a))
b = a
print(id(b))
# 1893403197936
# 1893403197936
hash([object])
Return the hash value of the object (if it has one). Hash values are integers. They are used to quickly compare dictionary keys during a dictionary lookup. Numeric values that compare equal have the same hash value (even if they are of different types, as is the case for 1 and 1.0).
返回对象的哈希值(如果有的话)。哈希值是整数。它们用于在字典查找期间快速比较字典键。比较相等的数值具有相同的哈希值(即使它们是不同类型的,如1和1.0)。
hash()函数对于能够计算哈希值的类型返回哈希值。
type(name, bases, dict)
The
type()
function is used to get the type of an object.type()函数用于获取对象的类型。
语法:
type(object) type(name, bases, dict)
When a single argument is passed to the type() function, it returns the type of the object. Its value is the same as the object.__class__ instance variable.
当单个参数传递给type()函数时,它返回对象的类型。它的值与对象相同。__class__实例变量。
a = 10
print(type(a))
# <class 'int'>
When three arguments are passed, it returns a new type object. It’s used to create a class dynamically on the fly.
当传递三个参数时,它会返回一个新的类型对象。它用于动态创建一个类。
- “name” string becomes the class name. It’s the same as the __name__ attribute of a class.“name”字符串成为类名。它与类的__name__属性相同。
- “bases” tuple specifies the base classes. It’s the same as the __bases__ attribute of the class.“base”元组指定基类。它与类的__bases__属性相同。
- “dict” dictionary helps create the class body. It’s the same as the __dict__ attribute of the class.“dict”字典有助于创建类体。它与类的__dict__属性相同。