Python标准库


系列文章:


文章目录

  • time库
    • 1. 获取现在时间
    • 2、时间戳与计时器
    • 3、格式化
  • random库
    • 1、随机种子
    • 2、产生随机整数
    • 3、产生随机浮点数
    • 4、序列用函数
    • 概率分布-高斯为例
  • collections库——容器数据类型
    • 1、nametuple 具名元组
    • 2、Counter 计数器工具
    • 3、deque双向队列
  • itertools库----迭代器
    • 1、排列组合迭代器
    • 2、拉链
    • 3、无穷迭代器
    • 4、其他


Python自身提供了比较丰富的生态,拿来即用,可极大的提高开发效率

time库

Python处理时间的标准库

1. 获取现在时间

  • time.localtime() 本地时间
  • time.gmtime() UTC世界统一时间
  • time.ctime() 本地时间的字符串
    北京时间比世界统一时间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=2022, tm_mon=7, tm_mday=20, tm_hour=15, tm_min=39, tm_sec=26, tm_wday=2, tm_yday=201, tm_isdst=0)
# t_UTC time.struct_time(tm_year=2022, tm_mon=7, tm_mday=20, tm_hour=7, tm_min=39, tm_sec=26, tm_wday=2, tm_yday=201, tm_isdst=0)

print(time.ctime())                  # 返回本地时间的字符串
# Wed Jul 20 15:40:18 2022

2、时间戳与计时器

  • time.time() 返回自纪元以来的秒数,记录sleep
  • time.perf_counter() 随意选取一个时间点,记录现在时间到该时间点的间隔,记录sleep
  • time.process_time() 随意选取一个时间点,记录现在时间到该时间点的间隔秒数,不记录sleep

perf_counter()精度较time()更高一些

import  time

t_1_start = time.time()
t_2_start = time.perf_counter()
t_3_start = time.process_time()
print(t_1_start) #1658303266.2639954
print(t_2_start) #0.024357
print(t_3_start) #0.03125

res = 0
for i in  range(100000):
    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))
# time方法:5.005秒
# perf_counter方法:5.003秒
# process_time方法:0.000秒

3、格式化

import  time

lctime = time.localtime()
print(time.strftime("%Y-%m-%d %A %H:%M:%S",lctime))
# 2022-07-20 Wednesday 16:07:11

random库

1、随机种子

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

seed(10)
print(random()) #0.5714025946899135
seed(10)
print(random()) #0.5714025946899135

print(random()) #0.4288890546751146

2、产生随机整数

  • randint(a,b) 产生[a,b]之间的随机整数
  • randrange(a) 产生[0,a)之间的随机整数
  • randrange(a, b, step) 产生[a,b)之间以step为步长的随机整数
numbers = [randint(1,10) for i in range(5)]
print(numbers) #[2, 4, 5, 10, 6]

numbers = [randrange(10) for i in range(5)]
print(numbers) #[7, 1, 0, 9, 6]

numbers = [randrange(0,10,2) for  i in range(5)]
print(numbers) #[8, 6, 2, 2, 0]

3、产生随机浮点数

  • random() 产生[0.0, 1.0] 之间的随机浮点数
  • uniform(a,b) 产生[a,b]之间的随机浮点数
from  random import  *

numbers = [random() for i in range(3)]
print(numbers) #[0.08235468836823401, 0.12703237322112282, 0.7141327625417357]

numbers = [uniform(2.1, 3.5) for i in range(3)]
print(numbers) #[2.1336464471499363, 2.9027448479264546, 3.449301362419453]

4、序列用函数

  • choice(seq) 从序列类型中随机返回一个元素
print(choice(['win', 'lose', 'draw'])) #draw

print(choice("Python")) #n
  • choices(seq, weights=None, k) 对序列类型进行k次重复采样,可设置权重
print(choices(['win', 'lose', 'draw'], k=10))
#['lose', 'win', 'draw', 'win', 'lose', 'draw', 'draw', 'lose', 'draw', 'lose']

print(choices(['win', 'lose', 'draw'],[4,4,2], k=10))
#['win', 'lose', 'win', 'win', 'win', 'win', 'lose', 'lose', 'lose', 'lose']
  • shuffle(seq) 将序列类型中元素随机排列,返回打乱后的序列
numbers = ["one", "two", "three", "four"]
shuffle(numbers)
print(numbers) #['two', 'one', 'four', 'three']
  • sample(pop, k) 从pop类型中随机选取k个元素,以列表类型返回
print(sample([10,20,30,40,50],k=3)) #[50, 40, 10]

概率分布-高斯为例

from  random import  *
import matplotlib.pyplot as  plt
res = [gauss(0, 1) for i in range(10000)]
plt.hist(res, bins=1000)
plt.show()

Python标准库_第1张图片
【例1】 用random库实现简单的微信红包分配

import random

def red_package(total, num):
    for i in range(1, num):
        ## 保证每个人获得红包的期望是total/num
        per = random.uniform(0.01, total/(num-i+1)*2)
        total = total - per
        print("第{}位红包金额: {:.2f}元".format(i, per))
    else:print("第{}位红包金额: {:.2f}元".format(num, total))

red_package(10,5)1位红包金额: 2.26元
第2位红包金额: 3.37元
第3位红包金额: 1.48元
第4位红包金额: 0.87元
第5位红包金额: 2.02

【例2】生产4位2由数字和英文字母构成的验证码

import random
import string

print(string.digits) #0123456789
print(string.ascii_letters) #abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
s = string.digits + string.ascii_letters
v = random.sample(s, 4)
print(v) #['z', 'v', 'R', 'o']
print(''.join(v)) #zvRo

collections库——容器数据类型

1、nametuple 具名元组

  • 点的坐标,紧看数据,很难直到表达的是一个点的坐标
    p = (1, 2)
  • 构建一个新的元组子类
    定义方法如下:typename是元组名字, field_names是域名
    collections.namedtuple(typename, field_names, *, rename=False, defaults=None, module=None)
import collections

point = collections.namedtuple("Point",["x","y"])
p = point(1, y=2)
print(p) #Point(x=1, y=2)
  • 可以调用属性
print(p.x) #1
print(p.y) #2
  • 有元组的性质
print(p[0]) #1
print(p[1]) #2
x, y = p
print(x,y) #1 2
  • 确实是元组的子类
print(isinstance(p,tuple)) #True

【例】模拟扑克牌

Card = collections.namedtuple("Card",["rank", "suit"])
ranks = [str(n) for n in range(2,11)] + list("JQKA")
print(ranks)
suits = "spades diamonds clubs hearts".split()
print(suits)
cards  = [Card(rank, suit) for rank in ranks for suit in  suits]
print(cards)
# [Card(rank='2', suit='spades'), Card(rank='2', suit='diamonds'), Card(rank='2', suit='clubs'), .....
# 洗牌
shuffle(cards)

# 随机抽一张牌
print(choice(cards)) #Card(rank='K', suit='hearts')

# 随机抽取多张牌
sample(cards, k=5)

2、Counter 计数器工具

from collections import Counter

s = "牛奶奶找刘奶奶买牛奶"
colors = ['red', 'blue', 'red', 'green', 'blue', 'blue']
cnt_str = Counter(s)
cnt_color = Counter(colors)

print(cnt_str)
# Counter({'奶': 5, '牛': 2, '找': 1, '刘': 1, '买': 1})

print(cnt_color)
# Counter({'blue': 3, 'red': 2, 'green': 1})
  • 是字典的一个子类
print(isinstance(Counter(), dict)) #True
  • 最常见的统计 most_common(n)
print(cnt_color.most_common(2)) #[('blue', 3), ('red', 2)]
  • 元素展开 elements()
print(list(cnt_str.elements())) 
#['牛', '牛', '奶', '奶', '奶', '奶', '奶', '找', '刘', '买']
  • 其他一些加减操作
c = Counter(a=3, b=1)
d = Counter(a=1,b=2)
print(c+d) #Counter({'a': 4, 'b': 3})

【例】从一副牌中抽取10张,大于10的比例有多少

from collections import Counter
from random import *
cards = collections.Counter(tens=16, low_card=36)
seen = sample(list(cards.elements()), k=10)
print(seen)
# ['low_card', 'tens', 'low_card', 'tens', 'low_card', 'tens', 'low_card', 'tens', 'low_card', 'low_card']
print(seen.count('tens')/10)# 0.4

3、deque双向队列

列表访问数据非常快,插入删除非常慢(通过移动元素实现),特别是insert(0,v)和pop(0),在列表开始进行的插入和删除操作
双向队列可以方便的在队列两边高效、快速地增加和删除操作

from collections import deque

d = deque('cde')
print(d) #deque(['c', 'd', 'e'])
d.append("f") #右侧增加
d.appendleft("b") #左侧添加

print(d)  #deque(['b', 'c', 'd', 'e', 'f'])
d.pop() #右侧删除
d.popleft() #左侧删除
print(d) #deque(['c', 'd', 'e'])

itertools库----迭代器

1、排列组合迭代器

1、 排列组合迭代器
(1) product 笛卡尔积

import  itertools
for i in  itertools.product('ABC', '01'):
    print(i)
# ('A', '0')
# ('A', '1')
# ('B', '0')
# ('B', '1')
# ('C', '0')
# ('C', '1')
for i in  itertools.product('ABC', repeat=3):
    print(i)
# ('A', 'A', 'A')
# ('A', 'A', 'B')
# ('A', 'A', 'C')
# ('A', 'B', 'A')
# ..........
# 
# ('C', 'C', 'A')
# ('C', 'C', 'B')
# ('C', 'C', 'C')

(2)permutations 排列

import  itertools
for i in itertools.permutations('ABCD',3): #3是排列的长度
    print(i)

# ('A', 'B', 'C')
# ('A', 'B', 'D')
# ('A', 'C', 'B')
# .....
# ('D', 'B', 'C')
# ('D', 'C', 'A')
# ('D', 'C', 'B')
import  itertools
for i in itertools.permutations(range(3)):
    print(i)

# (0, 1, 2)
# (0, 2, 1)
# (1, 0, 2)
# (1, 2, 0)
# (2, 0, 1)
# (2, 1, 0)

(3)combinations 组合

import  itertools
for i in itertools.combinations("ABCD", 2): #2是组合长度
    print(i)
# ('A', 'B')
# ('A', 'C')
# ('A', 'D')
# ('B', 'C')
# ('B', 'D')
# ('C', 'D')
import  itertools
for i in itertools.combinations(range(4), 3): #2是组合长度
    print(i)
# (0, 1, 2)
# (0, 1, 3)
# (0, 2, 3)
# (1, 2, 3)

(4)combinations_with_replacement 元素可重复组合

import  itertools
for i in itertools.combinations_with_replacement("ABC",2): #2是组合长度
    print(i)
# ('A', 'A')
# ('A', 'B')
# ('A', 'C')
# ('B', 'B')
# ('B', 'C')
# ('C', 'C')

2、拉链

(1)zip 短拉链

 # 注意zip是内置的,不需要加itertools
for i in zip("ABC","012","XYZ"):
    print(i)
# ('A', '0', 'X')
# ('B', '1', 'Y')
# ('C', '2', 'Z')
for i in zip("ABC",[0, 1, 2, 3, 4, 5]):
    print(i)
# ('A', 0)
# ('B', 1)
# ('C', 2)

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

import itertools

for i in itertools.zip_longest("ABC",[0, 1, 2, 3, 4, 5]):
    print(i)
# ('A', 0)
# ('B', 1)
# ('C', 2)
# (None, 3)
# (None, 4)
# (None, 5)
import itertools

for i in itertools.zip_longest("ABC",[0, 1, 2, 3, 4, 5],fillvalue="?"):
    print(i)
# ('A', 0)
# ('B', 1)
# ('C', 2)
# ('?', 3)
# ('?', 4)
# ('?', 5)

3、无穷迭代器

(1)count(start=0, step=1)——计数
创建一个迭代器,它从 start 值开始,返回均匀间隔的值

itertools.count(10)
10
11
12
.
.
.

(2)cycle(iterable)—循环
创建一个迭代器,返回 iterable 中所有元素,无限重复

print(itertools.cycle("ABC"))
A
B
C
A
B
C
.
.
.

(3)repeat(object,[,times])——重复
创建一个迭代器,不断重复 object 。除非设定参数 times ,否则将无限重复

for i in  itertools.repeat(10,5):
    print(i)
10
10
10
10
10

4、其他

(1)chain(iterables) ——锁链
把一组迭代对象串联起来,形成一个更大的迭代器

for i in  itertools.chain('ABC',[1,2,3],'PYTHON'):
    print(i,end="") #ABC123PYTHON

(2)enumerate(iterable, start=0) ——枚举(Python内置)
产出由2两个元素组成的元组,结构是(index, item), 其中index是从start开始,item从iterable中取

for i in  enumerate("Py", start=2):
    print(i)
# (2, 'P')
# (3, 'y')

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

for key, group in itertools.groupby('AAAABBBCCDAABBB'):
    print(key, list(group))
# A ['A', 'A', 'A', 'A']
# B ['B', 'B', 'B']
# C ['C', 'C']
# D ['D']
# A ['A', 'A']
# B ['B', 'B', 'B']
import itertools

animals = ["duck", "eagle", "rat", "giraffe", "bear", "bat", "dolphin", "shark", "lion"]
animals.sort(key=len)
print(animals)
# ['rat', 'bat', 'duck', 'bear', 'lion', 'eagle', 'shark', 'giraffe', 'dolphin']

for key, group in itertools.groupby(animals, key=len):
    print(key, list(group))
# 3 ['rat', 'bat']
# 4 ['duck', 'bear', 'lion']
# 5 ['eagle', 'shark']
# 7 ['giraffe', 'dolphin']

import itertools

animals = ["duck", "eagle", "rat", "giraffe", "bear", "bat", "dolphin", "shark", "lion"]
animals.sort(key=lambda x:x[0])
print(animals)
# ['bear', 'bat', 'duck', 'dolphin', 'eagle', 'giraffe', 'lion', 'rat', 'shark']
for key, group in itertools.groupby(animals, key=lambda x:x[0]):
    print(key, list(group))
# b ['bear', 'bat']
# d ['duck', 'dolphin']
# e ['eagle']
# g ['giraffe']
# l ['lion']
# r ['rat']
# s ['shark']

你可能感兴趣的:(Python,python,开发语言,人工智能)