文章目录
1 Python内置数据结构
Python内置了很多数据结构(容器),供我们直接进行使用,在学习结构之前,有一些小的知识点进行补充。
1.1 数值型
- int、float、complex、bool都是class、1,5.0,2+3j都是对象即实例
- int:Python3的int就是长整型,且没有大小限制,受限于内存区域大小
- float:有整数和小数部分组成。支持十进制和科学计数法表示。
- complex:有实属和虚数部分组成,实数部分和虚数部分都是浮点数
- bool:int的子类,仅有2个实例,True和False,其中True表示1,False表示0
In [2]: int(10.12) # 直接取整
Out[2]: 10
In [3]: int(-12)
Out[3]: -12
In [4]: float(10) # 转换为浮点数
Out[4]: 10.0
In [5]: float(-9)
Out[5]: -9.0
In [6]: bool(1) # 1表示True(非0都为True)
Out[6]: True
In [7]: bool(0) # 0表示False
Out[7]: False
1.2 math模块
数学之中,除了加减乘除四则运算之外,还有其它更多的运算,比如乘方、开方、对数运算等等,Python 提供了一个专门辅助计算的模块:math
,模块方法及常量如下:
math.ceil
:向上取整math.floor
:向下取整math.pi
:数字常量,圆周率math.pow
:返回x的y次方,即x**ypath.sqrt
:求x的平方根
In [22]: import math # 导入模块
In [23]: math.pi
Out[23]: 3.141592653589793
In [24]: math.pow(2,3) # 2**3
Out[24]: 8.0
In [25]: math.ceil(-10.6)
Out[25]: -10
In [26]: math.ceil(-10.5)
Out[26]: -10
In [27]: math.ceil(12.3)
Out[27]: 13
In [28]: math.floor(12.3)
Out[28]: 12
In [29]: math.floor(-12.3)
Out[29]: -13
In [32]: math.sqrt(10)
Out[32]: 3.1622776601683795
注意:
- int 取整:正负数都只取整数
- 整除(向下取整)
In [33]: int(-12.1) # 只会取整数部分
Out[33]: -12
In [34]: int(10.5)
Out[34]: 10
In [35]: 1//3 # 向下取整
Out[35]: 0
In [36]: 2//6
Out[36]: 0
In [37]: 20//6
Out[37]: 3
In [38]: 10//3
Out[38]: 3
1.3 round圆整
在Python中有一个round函数,用于对小数进行取整,不过在Python中的round有些特别,总结一句话就是4舍6入5取偶
。即当小数点后面的数字小于5
呢,会直接舍去
,大于5
呢,会直接进位
,等于5
呢,会取最近的偶数
。
In [39]: round(1.2)
Out[39]: 1
In [40]: round(-1.2)
Out[40]: -1
In [41]: round(1.5)