---恢复内容开始---python
Q: 你想对浮点数执行指定精度的舍入运算git
A: 简单的使用内置的round(value, ndigits)函数便可。算法
>>> round(1.23, 1) 1.2 >>> round(1.27, 1) 1.3 >>> round(-1.27, 1) -1.3 >>> round(1.25361,3) 1.254 >>>
当一个值恰好在两个边界的中间的时候, round
函数返回离它最近的偶数。 也就是说,对1.5或者2.5的舍入运算都会获得2。数组
>>> round(1.25) 2 >>> round(2.5) 2
传给 round()
函数的 ndigits
参数能够是负数,这种状况下, 舍入运算会做用在十位、百位、千位等上面。好比:安全
>>> a = 1627731 >>> round(a, -1) 1627730 >>> round(a, -2) 1627700 >>> round(a, -3) 1628000 >>>
区别:格式化()dom
>>> x = 1.23456 >>> format(x, '0.2f') '1.23' >>> format(x, '0.3f') '1.235' >>> 'value is {:0.3f}'.format(x) 'value is 1.235' >>>
decimal
模块函数
格式化输出单个数字的时候,可使用内置的 format()
函数,好比:spa
>>> x = 1234.56789 >>> # Two decimal places of accuracy >>> format(x, '0.2f') '1234.57' >>> # Right justified in 10 chars, one-digit accuracy >>> format(x, '>10.1f') ' 1234.6' >>> # Left justified >>> format(x, '<10.1f') '1234.6 ' >>> # Centered >>> format(x, '^10.1f') ' 1234.6 ' >>> # Inclusion of thousands separator >>> format(x, ',') '1,234.56789' >>> format(x, '0,.1f') '1,234.6' >>>
若是你想使用指数记法,将f改为e或者E(取决于指数输出的大小写形式)。好比:code
>>> format(x, 'e') '1.234568e+03' >>> format(x, '0.2E') '1.23E+03' >>>
bin()
,
oct()
或
hex()
函数
9. 大型数组运算orm
10.矩阵与线性代数运算
Q: 你想从一个序列中随机抽取若干元素,或者想生成几个随机数。
要想从一个序列中随机的抽取一个元素,可使用 random.choice()
:
>>> import random >>> values = [1, 2, 3, 4, 5, 6] >>> random.choice(values) 2 >>> random.choice(values) 3 >>> random.choice(values) 1 >>> random.choice(values) 4 >>> random.choice(values) 6 >>>
为了提取出N个不一样元素的样本用来作进一步的操做,可使用 random.sample()
:
>>> random.sample(values, 2) [6, 2] >>> random.sample(values, 2) [4, 3] >>> random.sample(values, 3) [4, 3, 1] >>> random.sample(values, 3) [5, 4, 1] >>>
若是你仅仅只是想打乱序列中元素的顺序,可使用 random.shuffle()
:
>>> random.shuffle(values) >>> values [2, 4, 6, 5, 3, 1] >>> random.shuffle(values) >>> values [3, 5, 2, 1, 6, 4] >>>
生成随机整数,请使用 random.randint()
:
>>> random.randint(0,10) 2 >>> random.randint(0,10) 5 >>> random.randint(0,10) 0 >>> random.randint(0,10) 7 >>> random.randint(0,10) 10 >>> random.randint(0,10) 3 >>>
为了生成0到1范围内均匀分布的浮点数,使用 random.random()
:
random
模块使用 Mersenne Twister 算法来计算生成随机数。这是一个肯定性算法, 可是你能够经过 random.seed()
函数修改初始化种子。
在 random
模块中的函数不该该用在和密码学相关的程序中。 若是你确实须要相似的功能,可使用ssl模块中相应的函数。 好比, ssl.RAND_bytes()
能够用来生成一个安全的随机字节序列。
13. 计算最后一个周五的日期
14. 计算当前月份的日期范围
15. 字符串转换为日期
16.结合时区的日期操做
---恢复内容结束---