python常用内置函数(一)
python常用内置函数(一)
- 与数学相关
- abs()
- min()
- max()
- divmod()
- 强制转化
- int()
- float()
- str()
- chr()
- ord()
- bool()
- list()
- tuple()
- dict()
与数学相关
abs()
功能:返回数字的绝对值。
参数:数值表达式,整数,浮点数,复数(返回模)。
实例
print(abs(-2))
print(abs(3))
print(abs(-4.5522))
print(abs(4+5j))
print(abs(complex(3, 4)))
print(abs(3-4))
输出
2
3
4.5522
6.4031242374328485
5.0
1
min()
功能:返回参数的最小值。
参数:序列,不支持复数(复数没有大小比较的概念)。
实例
print(min(2, 4, 5))
print(min(3+4, 43))
print(min(334, 45.55))
输出
2
7
45.55
max()
功能:返回参数的最大值。
参数:序列,不支持复数(复数没有大小比较的概念)。
实例
print(max(2, 4, 5))
print(max(abs(3+4j), 4))
print(max(334, 45.55))
输出
5
5.0
334
divmod()
功能:返回一个包含商和余数的元组。
参数:两个数字参数a,b,不支持复数。
实例
print(divmod(34, 43))
print(divmod(23, 3))
print(divmod(23, 45.24))
print(divmod(23, 3.1))
输出
(0, 34)
(7, 2)
(0.0, 23.0)
(7.0, 1.2999999999999994)
强制转化
int()
功能:将一个字符串或数字转换为整型。
参数:class int(x, base=10) x:待转化的参数,base:进制类型,默认为10进制
实例
print(int())
print(int("1234"))
print(int(234.234))
print(int('1000', base=2))
print(int('0xf', base=16))
print(int('a', base=16))
输出
0
1234
234
8
15
10
float()
功能:用于将整数和字符串转换成浮点数。
参数: 一个整数和字符串
实例
print(float())
print(float(234))
print(float("234.23"))
输出
0.0
234.0
234.23
str()
功能:返回一个字符串
参数: 一个对象
实例
print(str("123"))
print(str(1344))
print(str(1234.244))
print(str(2+3j))
print(str([24, 234, 24]))
print(str((2, 5, 66)))
print(str({ 's': 2}))
输出
123
1344
1234.244
(2+3j)
[24, 234, 24]
(2, 5, 66)
{ 's': 2}
chr()
功能:返回一个字符
参数: 一个整数
实例
print(chr(48))
print(chr(98))
输出
0
b
ord()
功能:返回 ASCII 数值,或者 Unicode 数值。
参数: 一个字符
实例
print(ord('a'))
print(ord('0'))
print(ord('中'))
输出
97
48
20013
bool()
功能:用于将给定参数转换为布尔类型,如果没有参数,返回 False。
参数: 一个参数
实例
print(bool(3==4))
print(bool())
print(bool(23))
print(bool("13"))
输出
False
False
True
True
list()
功能:用于将迭代对象转换为列表。
参数: 迭代对象
实例
print(list())
print(list("2345"))
print(list((1, 5, 'e')))
print(list({ 'a': 97, 'b': 98}))
输出
[]
['2', '3', '4', '5']
[1, 5, 'e']
['a', 'b']
tuple()
功能:用于将迭代对象转换为元组。
参数: 迭代对象
实例
print(tuple())
print(tuple("2345"))
print(tuple((1, 5, 'e')))
print(tuple({ 'a': 97, 'b': 98}))
输出
()
('2', '3', '4', '5')
(1, 5, 'e')
('a', 'b')
dict()
功能:返回元组。
参数: class dict(**kwarg)
class dict(mapping, **kwarg)
class dict(iterable, **kwarg)
**kwargs :关键字
mapping:元素的容器。
iterable :可迭代对象。
实例
print(dict())
print(dict([[1, 2], [2, 4]]))
print(dict([(1, 2), (2, 4)]))
print(dict(a=1, b=3, c=5))
print(dict(zip([2, 5, 6], [3, 5, 15])))
print(dict(((13, 34), (123, 45))))
输出
{ }
{ 1: 2, 2: 4}
{ 1: 2, 2: 4}
{ 'a': 1, 'b': 3, 'c': 5}
{ 2: 3, 5: 5, 6: 15}
{ 13: 34, 123: 45}
还没有评论,来说两句吧...