Python标准库——time,random,collections, itertools

579 阅读4分钟

1、time

获取本地时间

import time
time.localtime()
ime.gmtime()
time.ctime()

#获取时间戳和计时器
time.time()
time.perf_counter()
time.process_time()


lctime = time.localtime()
time.strftime("%Y-%m-%d %A %H:%M:%S", lctime) # 格式化输出


2、 random

from random import *
from random import *
seed(10)
print(random()) #0.5714025946899135
seed(10)
print(random()) #0.5714025946899135
seed(100)
print(random()) #0.1456692551041303
# 种子数一样,生成的随机数也一样
# 如果不设置种子数的话,则以当前时间为种子数
# 整数
randint(a,b). #[a,b]之间随机整数
randrange(a,b,step) #[a,b)之间以step为步长的随机整数
randrange(a,) #[0,a)之间随机整数

# 浮点数
random() # [0.0 ,1.0)之间的随机浮点数
uniform(a,b) #[a,b]  之间的随机浮点数

#序列用函数
choice(seq) # 序列中随机返回一个元素,可以是列表或者字符串
choices(seq,weight-None,k) # k为采样次数
choices( ["win","lose","draw"],[4,5,1],10) #  三个参数:序列/权重/采样次数
shuffle(seq)# 将序列中元素随机拍下,返回打乱后的序列
sample(pop,k)# 从pop类型中随机选取k个元素,返回一个列表

# 概率分布
gauss(mean,std) # 产生一个符合高斯分布的随机数

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


# 随机发红包
import random
def red_packet(total,num):
	for i in range(1,num):
		per = random.uniform(0.01,total/(num-i+1)*2)
		total -= per
		print("第 {}位红包金额:{:.2f}元".format(i,per))
	else:
		print("第 {}位红包金额:{:.2f}元".format(num, total)


#随机生成验证码
import random,string

 print(string.digits)
 print(string.ascii_letters)

 s = string.digits + string.ascii_letters

 v = random.sample(s,4)
 print(v)
 print("".join(v))

3、 collections

import collections
# collections.namedtuple(typename=,field_names=,rename=False,defaults=None,module=None)
Point = collections.namedtuple("point",["x","y"])
p = Point(1,7)
print(p)  #point(x=1, y=7)

print(p.x) #1
print(p.y) #7

print(p[0])  #1
print(p[1])   #7

a,b = p
print(a,b) #1 7

Counter函数

返回一个字典

from collections import Counter
s = "牛奶奶找刘奶奶买牛奶"
colors = ["red","blue","red","green","blue","blue"]
con_str = Counter(s)
con_color = Counter(colors)
print(con_str) #Counter({'奶': 5, '牛': 2, '找': 1, '刘': 1, '买': 1})
print(con_color) #Counter({'blue': 3, 'red': 2, 'green': 1})
print(con_color.most_common(2)) #[('blue', 3), ('red', 2)]

双向队列deque

from  collections import deque

d = deque("cde")
# print(d) #deque(['c', 'd', 'e'])

#增加元素
d.append("f")
d.append("g")
d.appendleft("b")
d.appendleft("a")
print(d) #deque(['a', 'b', 'c', 'd', 'e', 'f', 'g'])
# 删除元素
d.pop()
d.popleft()

4、 itertools

排列组合迭代器

笛卡尔积

import itertools

for i in itertools.product("abc","ABC"):
	print(i)
"""
('a', 'A')('a', 'B')('a', 'C')
('b', 'A')('b', 'B')('b', 'C')
('c', 'A')('c', 'B')('c', 'C')
"""

for i in itertools.product("abc",repeat=3):
	print(i)
"""
('a', 'a', 'a')('a', 'a', 'b')('a', 'a', 'c')('a', 'b', 'a')
('a', 'b', 'b')('a', 'b', 'c')('a', 'c', 'a')('a', 'c', 'b')
('a', 'c', 'c')('b', 'a', 'a')('b', 'a', 'b')('b', 'a', 'c')
('b', 'b', 'a')('b', 'b', 'b')('b', 'b', 'c')('b', 'c', 'a')
('b', 'c', 'b')('b', 'c', 'c')('c', 'a', 'a')('c', 'a', 'b')
('c', 'a', 'c')('c', 'b', 'a')('c', 'b', 'b')('c', 'b', 'c')
('c', 'c', 'b')('c', 'c', 'c')
"""

排列

import itertools
for i in itertools.permutations("abcd",3):
	print(i)
"""
('a', 'b', 'c')('a', 'b', 'd')('a', 'c', 'b')('a', 'c', 'd')
('a', 'd', 'b')('a', 'd', 'c')('b', 'a', 'c')('b', 'a', 'd')
('b', 'c', 'a')('b', 'c', 'd')('b', 'd', 'a')('b', 'd', 'c')
('c', 'a', 'b')('c', 'a', 'd')('c', 'b', 'a')('c', 'b', 'd')
('c', 'd', 'a')('c', 'd', 'b')('d', 'a', 'b')('d', 'a', 'c')
('d', 'b', 'a')('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)
"""

组合

不可重复组合

import itertools
for i in itertools.combinations("abc",2):
	print(i)
"""
('a', 'b')
('a', 'c')
('b', 'c')
"""

for i in itertools.combinations(range(4),3):
	print(i)
"""
(0, 1, 2)
(0, 1, 3)
(0, 2, 3)
(1, 2, 3)
"""

可重复组合

import itertools
for i in itertools.combinations_with_replacement("abc",2):
	print(i)
"""
('a', 'a')('a', 'b')
('a', 'c')('b', 'b')
('b', 'c')('c', 'c')
"""

for i in itertools.combinations_with_replacement(range(4),3):
	print(i)
"""
(0, 0, 0)(0, 0, 1)(0, 0, 2)(0, 0, 3)
(0, 1, 1)(0, 1, 2)(0, 1, 3)(0, 2, 2)
(0, 2, 3)(0, 3, 3)(1, 1, 1)(1, 1, 2)
(1, 1, 3)(1, 2, 2)(1, 2, 3)(1, 3, 3)
(2, 2, 2)(2, 2, 3)(2, 3, 3)(3, 3, 3)
"""

拉链zip

短拉链 (不用导入python包)

for i in zip("abc","ABC","1234"):
	print(i)

"""
('a', 'A', '1')
('b', 'B', '2')
('c', 'C', '3')
"""

长拉链(需要导入itertools包)

import itertools

for i in itertools.zip_longest("abc","ABCD","12345"):
	print(i)

"""
('a', 'A', '1')('b', 'B', '2')('c', 'C', '3')(None, 'D', '4')(None, None, '5')
"""

# 当有代替值
import itertools

for i in itertools.zip_longest("abc","ABCD","12345",fillvalue="#"):
	print(i)
"""
('a', 'A', '1')('b', 'B', '2')('c', 'C', '3')('#', 'D', '4')('#', '#', '5')
"""

无穷迭代器

itertools.count(start=0,step=1)

itertools.cycle(“ABC”)

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

其他

chain

import itertools

for i in itertools.chain("abc","efg",[1,2,3]):
	print(i) # a b c e f g 1 2 3  

enumerate(iterable,start)

for i in enumerate("python"):
	print(i) # 
"""
(0, 'p')(1, 'y')
(2, 't')(3, 'h')
(4, 'o')(5, 'n')
"""

groupby(iterable,key = None)

import itertools

for k,v in itertools.groupby("aaaabbbbbdbbdbbbdddccccccfffff"):
	print(k,list(v)) # v 返回一个迭代器
"""
a ['a', 'a', 'a', 'a']
b ['b', 'b', 'b', 'b', 'b']
d ['d']
b ['b', 'b']
d ['d']
b ['b', 'b', 'b']
d ['d', 'd', 'd']
c ['c', 'c', 'c', 'c', 'c', 'c']
f ['f', 'f', 'f', 'f', 'f']
"""



import itertools

animals = ["duck","tiger","rat","bear","bat","lion"]
animals.sort(key=lambda x:x[0]) #['bear', 'bat', 'duck', 'lion', 'rat', 'tiger']
print(animals)
for key,group in itertools.groupby(animals,key = lambda x:x[0]):
	print(key,list(group))
"""
b ['bear', 'bat']
d ['duck']
l ['lion']
r ['rat']
t ['tiger']
"""