Python time, random, collections, itertools 的基本用法
time库
import time
Python处理时间的标准库
- time.localtime() 本地时间
- time.gmtime() UTC世界统一时间,北京时间比这个统一时间早8个小时
- time.ctime() 返回本地时间的字符串
时间戳和计时器
- time.time() 返回自纪元以来的秒数,记录time.sleep()
- time.perf_counter() 随意取一个时间点到该时间点的间隔秒数,记录sleep
- time.process_time() 随意取,不记录sleep
格式化
time.strftime自定义格式化输出
1 | lctime = time.localtime() |
sleep
time.sleep() 以秒为单位
random库
Python通过random库提供各种伪随机数
随机种子——seed(a=None)
- 相同的种子会产生相同的随机数
- 如果不设置随机种子,以系统当前时间为默认值
产生随机整数
- randint(a, b) 产生[a,b]之间
- randrange(a) 产生[0,a)
- randrange(a, b, step) 产生[a, b), 以step为步长
产生随机浮点数
- random() 产生[0.0,1.0)
- uniform(a, b) 产生[a, b]
序列用函数
- choice(seq) 从seq返回一个
- choices(seq, weights=None, k) 对seq进行k次,可设置权重
- shuffle(seq) 将seq随机排列
- sample(pop, k) 从pop中随机可,以列表返回,k不能超过len(pop)
概率分布
guess(mean, std)
collecitons库
import collecitons
nametuple
collecitons.nametuple(typename, field_names, *, rename=False, default=None, module=None)
1 | Point = collecitons.nametuple("Point", ["x", "y"]) |
Counter
from collecitons import Counter
计数统计
Counter.most_common(n) 最常见的n个
Counter.elements() 展开
deque
双向队列
append()
appendleft()
pop()
popleft()
itertools库
排列组合迭代器
product——笛卡尔积
product(‘ABC’, “01”)
product(‘ABC’, repeat = 3)
permutations——排列
permutations(range(3))
combinations——组合
combinations(‘abcd’, 2)
combinations(range(4), 3)
combinations_with_replacement——元素可重复组合
拉链
zip——短拉链
zip(‘abc’, ‘012’, ‘xyz’)
长度不一时,执行到最短的对象处就停止
zip_longest——长拉链
zip_longest(‘abc’, ‘012345’, fillvalue=”?”)
长度不一时,执行到最长的对象处就停止,缺省元素用None或指定的字符替代
无穷迭代器
count(start=0, step=1) 计数
cycle(iterable) 循环
repeat(object, times) 重复
chain(iterables) 锁链
enumerate(iterable, start=0)——枚举(内置)
产出有两个元素组成的元组, 结构式(index, item),其中index从start开始,item从iterable中取
1
2for i in enumerate("pyhton", start = 1):
print(i)groupby(iterable, key=None)——分组
创建一个迭代器,按照key指定的方式,返回iterable中连续的键和组,一般来说要预先对数据进行排序,key为None默认把连续重复元素分组