目录
random 模块
random是取随机数的模块。在使用之前需要导入random模块
取随机小数
import random
print (random.random()) #取随机小数 0-1之间
print(random.uniform(n,m)) #m>n 取n-m之间的小数
取随机整数:彩票、抽奖
print(random.randint(1,2) #1,2交替出现
print(random.randrange(1,2))#1,2随机出现
print(random.randrange(1,200,2))#随机取奇数
从一个列表中随机抽取值:抽奖
L=['a','b',(1,2),100]
print(random.choice(L))#从列表中随机取值,可以随机取两次,两次的值可同可不同
print(random.sample(L,2))#从列表中随机抽取两个值,这两个值不会相同
打乱一个列表的顺序:洗牌
random.shuffle(L) #在原列表的基础上直接进行修改,节省空间
print(L) #['b', 100, (1, 2), 'a']
练习题
验证码
要求4位数字验证码
考虑字符串+循环
s=''
for i in range(4):
num=random.randint(0,9)
s+=str(num)#转换为字符串
print(s)
6位数字+字母的验证码。字母和数字是随机生成的
chr() 生成字母 65-90: A-Z 97-122 : a-z
s = ''
for i in range(6):
#生成随机的大写字母,小写字母,数字各一个
num=str(random.randint(0,9))
alpha_upper=chr(random.randint(65,90))
alpha_lower = chr(random.randint(97, 122))
res=random.choice([num,alpha_upper,alpha_lower])
s+=res
print(s)
改为函数形式
def code(n=6):
s = ''
for i in range(n):
# 生成随机的大写字母,小写字母,数字各一个
num = str(random.randint(0, 9))
alpha_upper = chr(random.randint(65, 90))
alpha_lower = chr(random.randint(97, 122))
res = random.choice([num, alpha_upper, alpha_lower])
s += res
return s
print(code())#生成4位
print(code(8)) #随机生成8位验证码
可指定生成全数字或数字+字母的验证码
def code(n,alpha=True):
s = ''
for i in range(n):
num = str(random.randint(0, 9))
if alpha:#True 执行if语句
alpha_upper = chr(random.randint(65, 90))
alpha_lower = chr(random.randint(97, 122))
num = random.choice([num, alpha_upper, alpha_lower])
s += num
return s
print(code(4,False))#生成4位全数字
print(code(8,alpha=True))#数字+字母
拼手气红包
发出一个固定金额的红包,由若干个人来抢,需要满足哪些规则?当然是如下了:
- 1.所有人抢到金额之和等于红包金额,不能超过,也不能少于。
- 2.每个人至少抢到一分钱。3.要保证所有人抢到金额的几率相等。
我们可采用二倍均值法来随机取数,原理如下:剩余红包金额为M,剩余人数为N,那么有如下公式:
每次抢到的金额 = 随机区间 (0.01, M / N X 2)这个公式,
保证了每次随机金额的平均值是相等的,不会因为抢红包的先后顺序而造成不公平。
举个例子:假设有10个人,红包总额100元。100/10X2 = 20, 所以第一个人的随机范围是(0.01,20 ),平均可以抢到10元。假设第一个人随机到10元,那么剩余金额是100-10 = 90 元。90/9X2 = 20, 所以第二个人的随机范围同样是(0.01,20 ),平均可以抢到10元。假设第二个人随机到10元,那么剩余金额是90-10 = 80 元。80/8X2 = 20, 所以第三个人的随机范围同样(0.01,20 ),平均可以抢到10元。以此类推,每一次随机范围的均值是相等的。最后一个人抢到的金额=总金额-被抢的总金额。
下面是我认为比较成功的代码:
import random
def hongbao(money,n):
k=n
sum=0#sum为前n个人抢得的总和,为了方便计算最后一个人的金额,初始值为0
round=n#剩余人次
while k>1:
current_money = money # 当前剩余的钱,初始值为money
for i in range(1,n+1):
get_money=random.uniform(0.01,int(2*current_money/round))
print('id[%s] have geted money %.2f'%(i,get_money))
current_money -= get_money
round -= 1
sum += get_money
k-=1
if k==1:#最后一个人,分得剩余的所有
print('id[%s] have geted money %s'%(n,money-sum))
hongbao(100,10)
结果:
id[1] have geted money 4.47
id[2] have geted money 17.41
id[3] have geted money 7.03
id[4] have geted money 5.08
id[5] have geted money 16.35
id[6] have geted money 5.44
id[7] have geted money 7.58
id[8] have geted money 13.60
id[9] have geted money 22.41
id[10] have geted money 0.37
上述方法 random.uniform取到的小数类似3.4455678864,虽然在输出时格式化处理,但并没有解决实际问题,并且最后一个人抢的最少,现在有一种更好的方法。
例如:200元钱发10个红包,看成一个0-200的数轴,中间9个断点,两断点之间的差再求和就是红包总金额200,(断点是随机生成的),用到生成器知识,类似取一个红包就生成一条记录,此方法是目前最好的方法。
import random
def red_packet(money,num):
money=money * 100 #将钱换为分
ret=random.sample(range(1,money),num-1) #红包个数num需要num-1个断点 9个数
ret.sort() #在原列表基础上排序
ret.insert(0,0) #将0加入列表
ret.append(money)#将money加入列表 列表有11个数正好可以截取10个数
for i in range(len(ret)-1):
yield (ret[i+1]-ret[i])/100 #根据索引取值再转换为元
ret_g=red_packet(200,10)
for money in ret_g:
print(money)
结果:
15.9
10.58
59.83
21.6
4.19
31.44
5.48
0.44
4.42
46.12
time 模块
和时间有关系的我们就要用到时间模块。在使用模块之前,应该先导入这个模块。
常用方法
import time
time.sleep(secs) #(线程)推迟指定的时间运行,单位为s
time.sleep(2) #睡眠2秒后,返回当前时间戳
#time.time() 获取当前时间戳
print(time.time()) #返回当前时间戳 #1558777461.315852
表示时间的三种方式
在python中,通常用三种方式来表示时间:时间戳、元组(struct_time)、格式化的时间字符串
(1)时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
print(time.time()) #返回当前时间戳 #1558777461.315852
(2)元组(struct_time):很多Python函数用一个元组装起来的9组数字处理时间
上述也就是struct_time元组。这种结构具有如下属性:
#时间元组:localtime将一个时间戳转换为当前时区的struct_time
struct_time=time.localtime()
print(struct_time)
#结果:
time.struct_time(tm_year=2019, tm_mon=5, tm_mday=25, tm_hour=18, tm_min=3, tm_sec=39, tm_wday=5, tm_yday=145, tm_isdst=0)
(3)格式化的时间字符串(Format String): ‘1999-12-06’ 、'2018.5.20'
我们可以使用 time 模块的 strftime 方法来格式化日期,:
time.strftime(format[, t])
print(time.strftime('%Y-%m-%d %H:%M:%S')) #str format time 2019-05-25 17:08:00
print(time.strftime('%y-%m-%d %H:%M:%S')) #19-05-25 17:08:43
print(time.strftime('%c')) #Sat May 25 17:09:15 2019
# 格式化成2016-03-20 11:45:39形式
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) #2019-05-25 17:59:57
小结:时间戳是计算机能够识别的时间;时间字符串是人能够看懂的时间;元组则是用来操作时间的
三种时间格式之间的转换
时间戳——>结构化时间
#time.gmtime(时间戳) UTC时间,与英国伦敦当地时间一致
#time.localtime(时间戳) 北京时间,与UTC相差8个小时
print(time.localtime(1500000000))
print(time.gmtime(1500000000))
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=10, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)
time.struct_time(tm_year=2017, tm_mon=7, tm_mday=14, tm_hour=2, tm_min=40, tm_sec=0, tm_wday=4, tm_yday=195, tm_isdst=0)
结构化——>时间戳
#结构化——>时间戳
#time.mktime(结构化时间)
time_tuple=time.localtime(1500000000)
timestamp=time.mktime(time_tuple)
print(timestamp)
1500000000.0
结构化——>字符串时间
#结构化——>字符串时间
#time.strftime("格式定义","结构化时间") 如果不传结构化时间参数,默认显示当前时间
print(time.strftime("%Y-%m-%d %X")) #2019-05-26 10:21:54
print(time.strftime("%Y-%m-%d",time.localtime(1500000000))) #2017-07-14
字符串时间——>结构化时间
#字符串时间——>结构化时间
#time.strptime("时间字符串","字符串对应格式")
print(time.strptime("2016.09.09","%Y.%m.%d"))
print(time.strptime("07/24/2018","%m/%d/%Y"))
time.struct_time(tm_year=2016, tm_mon=9, tm_mday=9, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=253, tm_isdst=-1)
time.struct_time(tm_year=2018, tm_mon=7, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=205, tm_isdst=-1)
#结构化时间——>%a %b %d %H:%M:%S %Y串
#time.asctime(结构化时间) 如果不传参数,直接返回当前时间的格式化串
print(time.asctime()) #Sun May 26 10:38:07 2019
time_tuple=time.localtime(1500000000)
print(time.asctime(time_tuple)) #Fri Jul 14 10:40:00 2017
#时间戳——>%a %b %d %H:%M:%S %Y串
#time.ctime(时间戳) 如果不传参数,直接返回当前时间的格式化串
print(time.ctime()) #Sun May 26 10:41:39 2019
print(time.ctime(1500000000)) #Fri Jul 14 10:40:00 2017
Python中时间日期格式化符号
- %y 两位数的年份表示(00-99)
- %Y 四位数的年份表示(000-9999)
- %m 月份(01-12)
- %d 月内中的一天(0-31)
- %H 24小时制小时数(0-23)
- %I 12小时制小时数(01-12)
- %M 分钟数(00=59)
- %S 秒(00-59)
- %a 本地简化星期名称
- %A 本地完整星期名称
- %b 本地简化的月份名称
- %B 本地完整的月份名称
- %c 本地相应的日期表示和时间表示
- %j 年内的一天(001-366)
- %p 本地A.M.或P.M.的等价符
- %U 一年中的星期数(00-53)星期天为星期的开始
- %w 星期(0-6),星期天为星期的开始
- %W 一年中的星期数(00-53)星期一为星期的开始
- %x 本地相应的日期表示
- %X 本地相应的时间表示
- %Z 当前时区的名称
- %% %号本身
练习题
1.请将当前时间的当前月1号的时间戳时间取出来-函数 2019-5-1
get_timestamp():
tuple_t=time.localtime() #获取当前结构化时间
struct_t=time.strptime('%s-%s-1' %(tuple_t.tm_year,tuple_t.tm_mon),'%Y-%m-%d') #2019-5-1结构化时间
timestamp_t=time.mktime(struct_t) #格式化——>时间戳
return timestamp_t
print(get_timestamp()) #1556640000.0
2. 计算时间差 #2019-5-25 22:10:8 2018-5-24 12:12:12 经过多少时分秒
str_time1='2018-5-24 12:12:12'
str_time2='2019-5-25 22:10:8'
struct_t1=time.strptime(str_time1,'%Y-%m-%d %H:%M:%S') #格式化时间——>结构化时间
struct_t2=time.strptime(str_time2,'%Y-%m-%d %H:%M:%S')
timestamp1=time.mktime(struct_t1) #结构化时间——>时间戳时间
timestamp2=time.mktime(struct_t2)
sub_time=timestamp2-timestamp1
gm_time=time.gmtime(sub_time) #转化为伦敦时间再-1970-1-1 00:00:00
print('2018-5-24 12:12:12与2019-5-25 22:10:8之间相差%d年%d月%d天%d小时%d分钟%d秒' %(gm_time.tm_year-1970,gm_time.tm_mon-1,gm_time.tm_mday-1,gm_time.tm_hour,gm_time.tm_min,gm_time.tm_sec))
2018-5-24 12:12:12与2019-5-25 22:10:8之间相差1年0月1天9小时57分钟56秒
日历(Calendar)模块
此模块的函数都是日历相关的,例如打印某月的字符月历
获取某月的日历
import calendar
cal=calendar.month(2019,5)
print("输出2019年5月的日历:\n",cal)
以上实例输出结果:
输出2019年5月的日历:
May 2019
Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
日历函数包含以下内置函数:
星期一是默认的每周第一天,星期天是默认的最后一天。更改设置需调用calendar.setfirstweekday()函数。
sys 模块
sys模块是与python解释器交互的一个接口
import sys
sys.argv 命令行参数List,第一个元素是程序本身路径
sys.exit(n) 退出程序,正常退出时exit(0),错误退出sys.exit(1)
sys.version 获取python解释器版本信息
sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform 返回操作系统平台名称
异常处理和status
import sys
try:
sys.exit(1)
except SystemExit as e:
print(e)
os 模块
os模块是与操作系统交互的一个窗口
import os
os.makedirs('dirname1/dirname2') 可生成多层递归目录
os.removedirs('dirname1') 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir('dirname') 生成单级目录;相当于shell中mkdir dirname
os.rmdir('dirname') 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir('dirname') 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() 删除一个文件
os.rename("oldname","newname") 重命名文件/目录
os.stat('path/filename') 获取文件/目录信息
os.system("bash command") 运行shell命令,直接显示
os.popen("bash command).read() 运行shell命令,获取执行结果
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir("dirname") 改变当前脚本工作目录;相当于shell下cd
os.path
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) 如果path存在,返回True;如果path不存在,返回False
os.path.isabs(path) 如果path是绝对路径,返回True
os.path.isfile(path) 如果path是一个存在的文件,返回True。否则返回False
os.path.isdir(path) 如果path是一个存在的目录,则返回True。否则返回False
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后访问时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
os.path.getsize(path) 返回path的大小
练习
1. 将path分割成目录和文件名二元组返回
import os
path=os.path.split('E:\pycharm file\Python学习之路\day18\sys模块.py')
print(path) #('E:\\pycharm file\\Python学习之路\\day18', 'sys模块.py')
2.获取某个文件所在目录的上一级目录。例如:\user\python\mywork 结果:\user\python
import os
file_path=os.path.dirname('E:\pycharm file\Python学习之路\day18\dir1\dir2') #其实就是os.path.split(path)的第一个元素 路径+文件
print(file_path)
E:\pycharm file\Python学习之路\day18\dir1
3.拼接目录:os.path.join
file_lst=os.listdir('E:\pycharm file\Python学习之路\day18')
for path in file_lst:
print(os.path.join('E:\pycharm file\Python学习之路\day18',path))
E:\pycharm file\Python学习之路\day18\dir1
E:\pycharm file\Python学习之路\day18\os模块.py
E:\pycharm file\Python学习之路\day18\random模块.py
E:\pycharm file\Python学习之路\day18\sys模块.py
E:\pycharm file\Python学习之路\day18\time模块.py
E:\pycharm file\Python学习之路\day18\__init__.py
E:\pycharm file\Python学习之路\day18\日历模块.py
4.使用os模块创建如下目录结构
import os
os.makedirs('glance/api')
os.makedirs('glance/cmd')
os.makedirs('glance/db')
open('glance/api/__init__.py','w').close()
open('glance/api/policy.py','w').close()
open('glance/api/version.py','w').close()
open('glance/cmd/__init__.py','w').close()
open('glance/cmd/manage.py','w').close()
open('glance/db/__init__.py','w').close()
open('glance/db/models.py','w').close()
5. 写一个copy函数,接收两个参数,第一个参数是源文件位置,第二个参数是目标位置,将源文件copy到目标位置
def copy(path1,path2):
filename=os.path.basename(path1) #获取源文件路径
if os.path.isfile(path1) and os.path.isdir(path2):
path2=os.path.join(path2,filename)
#判断这个文件之前是否存在
if os.path.exists(path2):
print('已有同名文件')
with open(path1,'rb')as f1,open(path2,'wb')as f2:
content=f1.read()
f2.write(content)
序列化模块
什么叫序列化——将原本的字典、列表等内容转换成一个字符串的过程叫做序列化。
序列化的目的
- 以某种存储形式使自定义
对象持久化; - 将对象从一个地方传到另一个地方;
- 使程序更具维护性。
json模块
json模块提供了四个功能:dumps、dump、loads、load
loads和dumps:在内存中做数据转换
- dumps 数据类型 转成 字符串 序列化
- loads 字符串 转成 数据类型 反序列化
import json
dic={'k1':'v1','k2':'v2','k3':'v3'}
str_dic=json.dumps(dic)#序列化:将一个字典转换成一个字符串
print(str_dic,type(str_dic)) #{"k1": "v1", "k2": "v2", "k3": "v3"} <class 'str'>
#注意:json转换完的字符串类型的字典中的字符串是由“”表示的
dic2=json.loads(str_dic)#反序列化:将一个字符串格式的字典转换成一个字典
#注意,要用json的loads功能处理的字符串类型的字典中的字符串必须由""表示
print(dic2,type(dic2))#{'k2': 'v2', 'k1': 'v1', 'k3': 'v3'} <class 'dict'>
list_dic=[1,['a','b','c'],3,{'k1':'v1','k2':'v2'}]
str_dic=json.dumps(list_dic)#也可以处理嵌套的数据类型
print(str_dic,type(str_dic)) #[1, ["a", "b", "c"], 3, {"k2": "v2", "k1": "v1"}] <class 'str'>
list_dic2=json.loads(str_dic)
print(list_dic2,type(list_dic2))#[1, ['a', 'b', 'c'], 3, {'k1': 'v1', 'k2': 'v2'}] <class 'list'>
load和dump:
- dump直接将数据类型写入文件——序列化;load直接从文件中读出 ——反序列化
- 不支持连续存储(可以dump很多次,但load会报错)
import json
f = open('json_file','w')
dic = {'k1':'v1','k2':'v2','k3':'v3'}
json.dump(dic,f) #dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件
f.close()
f = open('json_file')
dic2 = json.load(f) #load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回
f.close()
print(type(dic2),dic2)#<class 'dict'> {'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
ensure_ascii关键字参数:显示中文
import json
f = open('file','w')
json.dump({'国籍':'中国'},f)
ret = json.dumps({'国籍':'中国'})
f.write(ret+'\n')
json.dump({'国籍':'美国'},f,ensure_ascii=False)
ret = json.dumps({'国籍':'美国'},ensure_ascii=False)
f.write(ret+'\n')
f.close()
json格式化输出
data={'name':['张三','李四','王五'],'sex':'male','age':18}
json_dic=json.dumps(data,sort_keys=True,indent=4,separators=(',',':'),ensure_ascii=False)
print(json_dic)
结果:
{
"age":18,
"name":[
"张三",
"李四",
"王五"
],
"sex":"male"
}
其他参数说明
Skipkeys:默认值是False,如果dict的keys内的数据不是python的基本类型(str,unicode,int,long,float,bool,None),设置为False时,就会报TypeError的错误。此时设置成True,则会跳过这类key
ensure_ascii:,当它为True的时候,所有非ASCII码字符显示为\uXXXX序列,只需在dump时将ensure_ascii设置为False即可,此时存入json的中文即可正常显示。) If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse). If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity).
indent:应该是一个非负的整型,如果是0就是顶格分行显示,如果为空就是一行最紧凑显示,否则会换行且按照indent的数值显示前面的空白分行显示,这样打印出来的json数据也叫pretty-printed json
separators:分隔符,实际上是(item_separator, dict_separator)的一个元组,默认的就是(‘,’,’:’);这表示dictionary内keys之间用“,”隔开,而KEY和value之间用“:”隔开。 default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. sort_keys:将数据根据keys的值进行排序。 To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.
pickle模块
用于序列化的两个模块
- json,用于字符串 和 python数据类型间进行转换
- pickle,用于python特有的类型 和 python的数据类型间进行转换
pickle模块提供了四个功能:dumps、dump(序列化,存)、loads(反序列化,读)、load (不仅可以序列化字典,列表...可以把python中任意的数据类型序列化)
- 支持在python中几乎所有的数据类型
- dumps 序列化的结果只能是字节
- 只能在python中使用
- 在和文件操作时,需要用rb wb的模式打开文件
- 可以多次dump 和load
import pickle
dic = {'k1':'v1','k2':'v2','k3':'v3'}
str_dic = pickle.dumps(dic)
print(str_dic) #一串二进制内容
dic2 = pickle.loads(str_dic)
print(dic2) #字典
import time
struct_time = time.localtime(1000000000)
print(struct_time)
f = open('pickle_file','wb')
pickle.dump(struct_time,f)
f.close()
f = open('pickle_file','rb')
struct_time2 = pickle.load(f)
print(struct_time2.tm_year)
这时候机智的你又要说了,既然pickle如此强大,为什么还要学json呢?
这里我们要说明一下,json是一种所有的语言都可以识别的数据结构。
如果我们将一个字典或者序列化成了一个json存在文件里,那么java代码或者js代码也可以拿来用。
但是如果我们用pickle进行序列化,其他语言就不能读懂这是什么了~
所以,如果你序列化的内容是列表或者字典,我们非常推荐你使用json模块
但如果出于某种原因你不得不序列化其他的数据类型,而未来你还会用python对这个数据进行反序列化的话,那么就可以使用pickle
可以多次dum(存)和load(取)
实例:写一个用户注册登陆的程序,每一个用户的注册都要把用户名和密码用字典的格式写入文件userinfo,在登陆是再从文件中读取信息进行验证
字典:{'usr':'alex','pwd':'alx45'}
import pickle
def register():
usr = input('username : ')
pwd = input('password : ')
dic ={'usr':'alex','pwd':'alx45'}
with open('userinfo', 'ab')as f:
pickle.dump(dic, f)
print('注册成功')
def login():
usr = input('username : ')
pwd = input('password : ')
with open('userinfo', 'rb')as f:
while True:
try:
dic = pickle.load(f)
if dic['usr'] == usr and dic['pwd'] == pwd:
print('登陆成功')
break
except EOFError:
print('登陆失败')
break
register()
login()