0%

Python time, random, collections, itertools基本用法

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
2
lctime = time.localtime()
time.strftime("%Y-%m-%d %A %H:%M:%S", lctime)

sleep

time.sleep() 以秒为单位

random库

Python通过random库提供各种伪随机数

随机种子——seed(a=None)

  1. 相同的种子会产生相同的随机数
  2. 如果不设置随机种子,以系统当前时间为默认值

产生随机整数

  1. randint(a, b) 产生[a,b]之间
  2. randrange(a) 产生[0,a)
  3. randrange(a, b, step) 产生[a, b), 以step为步长

产生随机浮点数

  1. random() 产生[0.0,1.0)
  2. uniform(a, b) 产生[a, b]

序列用函数

  1. choice(seq) 从seq返回一个
  2. choices(seq, weights=None, k) 对seq进行k次,可设置权重
  3. shuffle(seq) 将seq随机排列
  4. 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
2
3
4
5
6
7
8
9
10
Point = collecitons.nametuple("Point", ["x", "y"])
p = Point(1, y=2)
p # Point(x=1, y=2)
# 可以调用属性
print(p.x) # 1
# 有元组的性质
print(p[0]) # 1
x, y = p
print(x) # 1

Counter

from collecitons import Counter

计数统计

Counter.most_common(n) 最常见的n个

Counter.elements() 展开

deque

双向队列

append()

appendleft()

pop()

popleft()

itertools库

排列组合迭代器

  1. product——笛卡尔积

    product(‘ABC’, “01”)

    product(‘ABC’, repeat = 3)

  2. permutations——排列

    permutations(range(3))

  3. combinations——组合

    combinations(‘abcd’, 2)

    combinations(range(4), 3)

  4. combinations_with_replacement——元素可重复组合

拉链

  1. zip——短拉链

    zip(‘abc’, ‘012’, ‘xyz’)

    长度不一时,执行到最短的对象处就停止

  2. zip_longest——长拉链

    zip_longest(‘abc’, ‘012345’, fillvalue=”?”)

    长度不一时,执行到最长的对象处就停止,缺省元素用None或指定的字符替代

无穷迭代器

  1. count(start=0, step=1) 计数

  2. cycle(iterable) 循环

  3. repeat(object, times) 重复

  4. chain(iterables) 锁链

  5. enumerate(iterable, start=0)——枚举(内置)

    产出有两个元素组成的元组, 结构式(index, item),其中index从start开始,item从iterable中取

    1
    2
    for i in enumerate("pyhton", start = 1):
    print(i)
  6. groupby(iterable, key=None)——分组

    创建一个迭代器,按照key指定的方式,返回iterable中连续的键和组,一般来说要预先对数据进行排序,key为None默认把连续重复元素分组