Python标准库-1/2

一如既往,列出值得关注的部分。

1.Math模块

1.1 常见常量

import math
print('math.pi ' math.pi)
print('math.e '  math.e)

/>>>>>/
math.pi 3.141592653589793
math.e 2.718281828459045

import math
print("math.pi = %.30f " % math.pi)
print('math.e = %.30f'  %math.e)  

/>>>>>/
math.pi = 3.141592653589793115997963468544
math.e = 2.718281828459045090795598298428
注意这个很蠢的小细节。没有逗号。
math下的常量只要需要,可以提供到很高的精度。


1.2 整数转换

math.trunc() 截尾
math.floor() 向下取整
math.ceil() 向上取整

1.3 常用计算

1)math.fabs()

2)

values = [ 0.1 ] * 10
sum(values)

/>>>>>/
0.9999999999999999

math提供了一个精确的函数math.fsum(),可以避免重复大量计算浮点数加减时带来的可以避免的误差;

import math
values= [0.1] * 10
print(math.fsum(values))

/>>>>>/
1.0

3)math.factorial()

import math
values= [0.1] * 10
for i in [0,1.0,2.0,3.0,4.0,5.0]:
    print(i,' ',math.factorial(i))

/>>>>>/
0 1
1.0 1
2.0 2
3.0 6
4.0 24
5.0 120
[Finished in 0.1s]

扫描二维码关注公众号,回复: 1435371 查看本文章

4)math.log(),以e为底
math.log(8,2)=3.0
math.pow(2,3)=8.0

2 时间

import time
print(time.time())

1525270631.9043953

import time
print(time.ctime())

Wed May 2 22:17:36 2018

import time
t=time.localtime()
print(t)

time.struct_time(tm_year=2018, tm_mon=5, tm_mday=2, tm_hour=22, tm_min=18, tm_sec=48, tm_wday=2, tm_yday=122, tm_isdst=0)

import time
t=time.localtime()
print(t.tm_year)

2018
与之相对的还有time.gmtime,
就是标准时间

3 random

1)random.random()
random.seed(5)
random.randint(1,500)
random.randint(1,1000,100)
2)random.shuffle、choice、sample
shuffle原地修改列表的顺序,需要保留原始数据的话需要提前copy深拷贝一份备份。
choice就是选取一个值
random.sample(a,5),这里的5就是取几个样的参数。
random的分布部分暂时搁置,以后学。

还有部分glob、fileinput、bz2、gzip、pprint、traceback、JSON后面写。

猜你喜欢

转载自blog.csdn.net/zhubozhen/article/details/80186351