第十章 Python标准库
Python自身提供了比较丰富的生态,拿来即用,可极大的提高开发效率
10.1 time库
Python处理时间的标准库
1、获取现在时间
(1)time.localtime() 本地时间
(2)time.gmtime() UTC世界统一时间
北京时间比时间统一时间UTC早8个小时
import time
t_local = time.localtime()
t_UTC = time.gmtime()
print("t_local", t_local) # 本地时间
print("t_UTC", t_UTC) # UTC统一时间
t_local time.struct_time(tm_year=2019, tm_mon=8, tm_mday=29, tm_hour=16, tm_min=43, tm_sec=37, tm_wday=3, tm_yday=241, tm_isdst=0)
t_UTC time.struct_time(tm_year=2019, tm_mon=8, tm_mday=29, tm_hour=8, tm_min=43, tm_sec=37, tm_wday=3, tm_yday=241, tm_isdst=0)
time.ctime() # 返回本地时间的字符串
'Thu Aug 29 16:44:52 2019'
2、时间戳与计时器
(1)time.time() 返回自纪元以来的秒数,记录sleep
(2)time.perf_counter() 随意选取一个时间点,记录现在时间到该时间点的间隔秒数,记录sleep
(3)time.process_time() 随意选取一个时间点,记录现在时间到该时间点的间隔秒数,不记录sleep
perf_counter()精度较time()更高一些
t_1_start = time.time()
t_2_start = time.perf_counter()
t_3_start = time.process_time()
print(t_1_start)
print(t_2_start)
print(t_3_start)
res = 0
for i in range(1000000):
res += i
time.sleep(5)
t_1_end = time.time()
t_2_end = time.perf_counter()
t_3_end = time.process_time()
print("time方法:{:.3f}秒".format(t_1_end-t_1_start))
print("perf_counter方法:{:.3f}秒".format(t_2_end-t_2_start))
print("process_time方法:{:.3f}秒".format(t_3_end-t_3_start))
1567068710.7269545
6009.0814064
2.25
time方法:5.128秒
perf_counter方法:5.128秒
process_time方法:0.125秒
3、格式化
(1)time.strftime 自定义格式化输出
lctime = time.localtime()
time.strftime("%Y-%m-%d %A %H:%M:%S", lctime)
'2019-08-29 Thursday 16:54:35'
4、睡觉觉
(1)time.sleep()
10.2 random库
随机数在计算机应用中十分常见
Python通过random库提供各种伪随机数
基本可以用于除加密解密算法外的大多数工程应用
1、随机种子——seed(a=None)
(1)相同种子会产生相同的随机数
(2)如果不设置随机种子,以系统当前时间为默认值
from random import *
seed(10)
print(random())
seed(10)
print(random())
0.5714025946899135
0.5714025946899135
print(random())
0.20609823213950174
2、产生随机整数
(1)randint(a, b)——产生[a, b]之间的随机整数
numbers = [randint(1,10) for i in range(10)]
numbers
[3, 5, 6, 3, 8, 4, 8, 10, 7, 1]
(2)randrange(a)——产生[0, a)之间的随机整数
numbers = [randrange(10) for i in range(10)]
numbers
[6, 3, 0, 0, 7, 4, 9, 1, 8, 1]
(3)randrange(a, b, step)——产生[a, b)之间以setp为步长的随机整数
numbers = [randrange(0, 10, 2) for i in range(10)]
numbers
[2, 6, 8, 4, 8, 2, 0, 0, 6, 2]
3、产生随机浮点数
(1)random()——产生[0.0, 1.0)之间的随机浮点数
numbers = [random() for i in range(10)]
numbers
[0.9819392547566425,
0.19092611184488173,
0.3486810954900942,
0.9704866291141572,
0.4456072691491385,
0.6807895695768549,
0.14351321471670841,
0.5218569500629634,
0.8648825892767497,
0.26702706855337954]
(2)uniform(a, b)——产生[a, b]之间的随机浮点数
numbers = [uniform(2.1, 3.5) for i in range(10)]
numbers
[2.523598043850906,
3.0245903649048116,
3.4202356766870463,
2.344031169179946,
2.3465252151503173,
3.181989084829388,
2.5592895031615703,
2.413131937436849,
2.8627907782614415,
2.16114212173462]
4、序列用函数
(1)choice(seq)——从序列类型中随机返回一个元素
choice(['win', 'lose', 'draw'])
'draw'
choice("python")
'h'
(2)choices(seq,weights=None, k)——对序列类型进行k次重复采样,可设置权重
choices(['win', 'lose', 'draw'], k=