环境小硕的转化之路-20-random,time,sys,os模块

前言

对伪生化的十字军正式展开,士气高昂.

random模块

import random
print(1,random.random())#取0~1之间的随机数
print(2,random.uniform(1,2))#接受1,2(可设置范围)之间的随机数
print(3,random.randint(1,2))#接受范围内的整数,顾头也顾尾
print(4,random.randrange(1,2))#接受范围内的整数,顾头不顾尾
print(5,random.randrange(1,200,2))#接受1-200范围内的奇整数
lst = ['a','b','c',1,2,3]
print(6,random.choice(lst))#从lst中随机抽取一个值
print(7,random.sample(lst,2))#从列表中随机抽取2个值(不会重复),输出列表
random.shuffle(lst)#洗牌
print(8,lst)#打乱列表顺序(在原来的基础上打乱),可以节省空间

  

输出结果

1 0.05030177510722167
2 1.1372945334797908
3 2
4 1
5 5
6 1
7 [1, 2]
8 [3, 'a', 'b', 2, 'c', 1]

  

练习题

题1:生成6位验证码,数字加字母(大小写都有)混合

答:

def code(n = 6,alpha = True):
    s = ''
    for i in range(n):
        num = str(random.randint(0,9))
        if alpha:#如果alpha flag开启则开始填入数字
            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

  

题2:发红包:用户输入红包数量和钱数,随机分配金额

法1:本人原创
def  red_wrapper(money,number):
    lst = []
    averange_money = float(money)/int(number)#将红包金额均分
    for i in range(int(number)):
        lst.append(averange_money)
    for obj in lst:
        random_number= round(random.uniform((0,obj-0.01),2)#生成一个列表元素里元素数值范围内的随机数
            lst[lst.index(obj)] = obj - random_number
            random_postition = random.randint(0,int(number) - 1)#元素值减去这个随机数.
            lst[random_postition] = lst[random_postition] + random_number#列表中其它一个随机位置的元素加上这个随机数
    return random.shuffle(lst)
ret = red_wrapper(input('请输入红包总金额'),input('请输入红包数量'))
print(ret)

  

法2:老师原创(目前看来是最好的算法)
import random
#采用的是数轴的思想,把数轴分成10段(10段长度不同),每段长就是每个红包钱数.
def red_packet(money,num):#总金额以及红包数
    money = money * 100#为了规避小数省略的问题,先乘个100用整数来计算.
    ret = random.sample(range(1,money),num-1)#在金额范围内取红包数减一个点.
    ret.sort()
    ret.insert(0,0)#插入0点
    ret.append(money)
    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)

  

法3:学霸原创,按照百分比计算.
import random
def Bonus(person,money):  # 5,200
    dict_person_money = {}
    for i in range(person):
        num = random.randint(1,100)  # 99 99 99 99 99
        dict_person_money["Person%s"%(i+1)] = num  # person1:99
    num_sum = 0
    for i in dict_person_money:
        num_sum += dict_person_money[i]  # 5 * 99 = 495
    for i in dict_person_money:    # 99/495 1/5 * 200 = 40
        x =round(dict_person_money[i]/num_sum*money,2)
        dict_person_money[i] = '$%s'%x
    return dict_person_money

  

time模块

时间戳时间(电脑看的)-结构化时间-字符串时间(人类看的)的转化图

主要的内容

import time
#time模块主要和时间打交道的
#1.sleep
#time.sleep()#程序走到这会大约停2s
#2.时间格式
    #a.时间戳时间
print(1,time.time())#1569035129.6580648 python世界里表示时间的第二种形式(浮点类型).以s为单位计时.
#1970.1.1号到现在的过了多少s,叫作时间戳时间,程序和人打交道必须有格式化时间.时间戳时间给机器计算用的.
    #b.字符串时间
print(2,time.strftime('%Y-%m-%d %H:%M:%S')) #叫作str format time,有点像占位符.叫作结构化时间2019-09-21 14:45:12

print(3,time.strftime('%c'))#Sat Sep 21 14:46:34 2019 歪果人喜欢的格式
    #c.结构化时间(作为字符串时间和时间戳时间给人使用的)
print(4,time.localtime())#tm_isdst = 0 是否夏令时(夏天早2h,秋天晚2h)
ret = time.localtime()
print(ret.tm_hour)#local.time里面可以取出当前小时数
#时间戳换成字符串时间
print(5,time.localtime(time.time()))#转换成了结构化时间
print(6,time.gmtime(time.time()))#转换成了伦敦结构化时间
struct_time1 =  time.gmtime(time.time())
print(7,time.strftime('%Y-%m-%d %H:%M:%S',struct_time1 ))#转换成了string_time
#字符串时间转时间戳
current_time = '2019-9-21'
struct_time = time.strptime(current_time,'%Y-%m-%d')
print(8,struct_time)#string_parse_time parse的意思是作句法分析.
print(9,time.mktime(struct_time),type(time.mktime(struct_time)))#将struct_time 变成 time_stamp

  

练习题

# 1.查看2000000000表示的年月日
# 2.查看2008-8-8转换成时间戳时间
# 3.将当时间的当前月的1号的时间戳时间截取出来 - 搞成一个函数
# 4.计算时间差2018-8-19 22:10:8 -> 2018-8-20 11:07:3 经过的了多少时,分,秒

#1
struct_time_1 = time.localtime(2000000000)
print('练习题1',time.strftime('%Y-%m-%d %H:%M:%S',struct_time_1))
#2
struct_time_2 = time.strptime('2008-8-8','%Y-%m-%d')
print('练习题2',time.mktime(struct_time_2))
#3
print(type(struct_time_2))
def get_the_timestamp(date_str):
#思路1:利用时间戳的差值
    # struct_time = time.strptime(date_str,'%Y-%m-%d')
    # minus_second = struct_time.tm_mday*24*60
    # time_stamp = time.mktime(struct_time)
    # return time_stamp - minus_second
#思路2:取结构化时间的值计算
    struct_time = time.strptime(date_str,'%Y-%m-%d')
    target_struct_time = time.strptime('%s-%s-1'%(struct_time.tm_year,struct_time.tm_mon),'%Y-%m-%d')
    return time.mktime(target_struct_time)
print('练习题3:',get_the_timestamp('2018-3-3'))
#4
def get_the_time_difference(fomertime,latetime):
    fomer_struct_time = time.strptime(fomertime,'%Y-%m-%d')
    late_struct_time = time.strptime(latetime,'%Y-%m-%d')
    fomer_time_stamp = time.mktime(fomer_struct_time)
    late_time_stamp = time.mktime(late_struct_time)
    res_seconds = late_time_stamp - fomer_time_stamp
思路1:自己编个函数计算
     if res_seconds<0:
         return print('输入错误')
     else :
         res_second,res_minutes = divmod(res_seconds,60)[1],divmod(res_seconds,60)[0]
         res_minute,res_hours = divmod(res_minutes,60)[1],divmod(res_minutes,60)[0]
         res_hour,res_days = divmod(res_hours,24)[1],divmod(res_hours,24)[0]
         return print('作业题4:'+'差了:%s天,%s小时,,%s分钟%s秒'%(res_days,res_hour,res_minute,res_second))

#思路2: 变成结构时间和1970-1-1相减(老师的方法)
    upper_time_stamp = time.gmtime(res_seconds)
    return print('作业题4:过去了%s年%s月%s日%s小时%s分%s秒'%(upper_time_stamp.tm_year-1970,
                                              upper_time_stamp.tm_mon-1,upper_time_stamp.tm_mday-1,
                                              upper_time_stamp.tm_hour,upper_time_stamp.tm_min,
                                              upper_time_stamp.tm_hour))
get_the_time_difference('2018-3-3','2018-3-6')

  

sys模块

主要的内容

#主要的三个命令:
#sys.argv
#sys.path
#sys.modules

#sys模块是和python解释器打交道.

import sys
import re
print(sys.argv)#argv第一个参数是这个python命令后面的值(在cmd 模式下 )

#作业:用sys.argv做一个完整的登陆功能.(pass待做)
# print(sys.argv[0])
# print(sys.argv[1])
# print(sys.argv[2])
#1.程序员 运维人员常在命令行运行代码
#2.操作系统:程序启动起来本质上是cpu执行指令,多个程序抢cpu运算力,input相当于在这个线程陷入等待,别的程序就会挤占
#现有程序的运算力.(程序阻塞就会退出cpu竞争)

print(sys.path)#是一个列表,里面存的都是文件夹的绝对路径.
#出现的路径是根据py安装路径拼接的.可以找模块的路径.
#模块是一堆文件,是存在硬盘上的.但是在使用的时候会执行import->这个模块才到内存中.
#一个模块能否被顺利导入全看sys.path
#学习自定义模块,导入模块的时候还需要继续关注sys.path
print(sys.modules['re'])#导入到内存中所有模块的名字:这个模块的命名空间(内存地址)
#等同于:
print(re)#可以在后面加方法.

  

os模块

主要的内容1

import os#os是和操作系统交互的模块
# os.makedirs('dir1/dir2')#可生成多层递归目录
# os.mkdir('dir3')#只能生成单层目录
# os.mkdir('dir3/dir4')
# os.rmdir('dir3/dir4')#删除某一个文件夹,删除了dir4
# os.removedirs('dir3/dir4')#删除多个文件夹,dir3和dir4全没了.
# os.rename('oldname','newname'(目录))
#注意:rmdir和removedirs都只能删空文件夹.
#如果想删带有文件的文件夹,得先remove掉文件,再用removedirs或rmdir
print(os.listdir(r'C:\Users\Administrator\PycharmProjects\全栈学习\day18'))#当前目录下所有文件夹和文件
file_list = os.listdir(r'C:\Users\Administrator\PycharmProjects\全栈学习\day18')
# for i in file_list:
#     final_path = '\\'.join([r'C:\Users\Administrator\PycharmProjects\全栈学习\day18',i])
#     print(final_path)
#但是linux连接符是/,os模块有专门处理路径的函数
for i in file_list:
    print(os.path.join(r'C:\Users\Administrator\PycharmProjects\全栈学习\day18',i))#再linux上也能使用
#os.path处理路径的方法都可以跨平台
print(os.stat(r'C:\Users\Administrator\PycharmProjects\全栈学习\day18'))#获得文件的信息
#os.stat_result(st_mode=16895, st_ino=2814749767131200, st_dev=1895634910, st_nlink=1, st_uid=0, st_gid=0, st_size=4096,
# st_atime=1569066873, st_mtime=1569066873, st_ctime=1568981250)在操作系统里面存文件的文件信息.
# st_mode: inode 保护模式
# st_ino: inode 节点号。
# st_dev: inode 驻留的设备。
# st_nlink: inode 的链接数。
# st_uid: 所有者的用户ID。
# st_gid: 所有者的组ID。
# st_size: 普通文件以字节为单位的大小;包含等待某些特殊文件的数据。
# st_atime: 上次访问的时间。
# st_mtime: 最后一次修改的时间。
# st_ctime: 由操作系统报告的"ctime"。在某些系统上(如Unix)是最新的元数据更改的时间,在其它系统上(如Windows)是创建时间(详细信息参见平台的文档)。
os.system('dir')#执行操作系统的命令,没有返回值.程序要处理这些路径,适合去做实际的操作,例如删除一个文件,创建一个文件夹.
ret = os.popen('dir')#执行字符串数据类型的命令行代码.(exec和eval执行的是字符串数据类型的python代码)
print(ret)#有返回值,为一个内存地址
print(ret.read())#即可查看
os.chdir(r'C:\Users\Administrator\PycharmProjects')#无论当前工作目录在哪,都会把工作目录切换到这个路径下.
ret1 = os.popen('dir')
print('--->',ret1.read())
print(os.getcwd())#current work dir获取当前执行程序的文件路径,当前工作目录.并不是指当前文件所在目录,而是指当前文件是在哪个目录下执行的.
主要的内容2

  

主要的内容2

path = os.path.abspath('01os模块.py')
print(1,path) #1.返回path规范化的绝对路径,path是绝对路径也可以是相对路径(同级目录下的).2.把路径中不符合规范的斜杠改成操作系统默认的格式.
print(2,os.path.split(path))#输出一个元组,将文件最后一级切割到第二位.(把路径分成两段)

print(3,os.path.dirname(path)) #返回path的目录。其实就是os.path.split(path)的第一个元素
print(4,os.path.basename(path)) #返回path最后的文件名。如果path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
print(5,os.path.exists(path))  #如果path存在,返回True;如果path不存在,返回False,用于和用户交互.
print(6,os.path.isabs(path))  #如果path是绝对路径,返回True
print(7,os.path.isfile(path))  #如果path是一个存在的文件,返回True。否则返回False
print(8,os.path.isdir(path))  #如果path是一个存在的目录,则返回True。否则返回False
#os.path.join(path1[, path2[, ...]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
print(9,os.path.getatime(path))  #返回path所指向的文件或者目录的最后访问时间,保证各个服务器的同步.偏向于自动化运维.
print(10,os.path.getmtime(path))  #返回path所指向的文件或者目录的最后修改时间
print(11,os.path.getsize(path)) #返回path的大小(字节大小),但所有的文件夹所有至少是4096字节的倍数.使用py
#无法统计文件夹的大小.
#但是有这个需求
#都是4096倍数的原因:操作系统没有文件夹的概念,但是新建文件的时候,他会在某处开辟一块空间用于存储文件夹的信息(名字,创建时间等)
#当扩展空间的形式是原来开辟空间空间加倍.
#统计文件夹的大小:拿到所有文件夹和文件,如果是文件就取大小,如果是文件夹就去文件夹中取文件.

  

主要的内容3

import os
os.path.getsize(r'C:\Users\Administrator\PycharmProjects\全栈学习\day16')#python命令
# dir 'C:\Users\Administrator\PycharmProjects\全栈学习\day16' \C 操作系统的命令行

#os.listdir python显示所有文件夹
#dir 命令行显示所有文件夹
#os.system('dir')#使用python语言直接执行操作系统的命令
#os.popen('dir') #执行字符串数据类型的操作系统命令并返回结果
#os.listdir('C:\Users\Administrator\PycharmProjects\全栈学习\day16')#使用python语言os模块提供的方法简介调用了操作系统的命令
#python是运行在操作系统上的,和操作系统离得最近的是操作系统命令.
#python上的一行代码代表在操作系统中对应的实行了一个命令,于是就拿到了文件大小.
#python -->调用操作系统的命令-->python-->指挥操作系统
# 可能会有两周时间去学习linux操作系统

#getcwd 获取当前执行命令的时候所在目录
#chdir 修改当前执行命令的所在目录,dir为例子.
# os模块做的事情
    #定制很多方法,间接帮助你去调用操作系统的命令 获得结果
    #然后帮助你分析整理我们需要的数据类型形态
#也可以用os.popen和os.system直接调用操作系统的命令获得结果
    #但是 得自己分析和整理
#用os模块的方法本身能完成的功能用定制好的方法就够了.
#若os模块定制好的功能不够用,而刚好操作系统的命令可以很好帮助我们解决问题,这时候就用os.popen或os.system

  

posted @ 2019-10-24 13:28  negu  阅读(122)  评论(0编辑  收藏  举报