模块二;具名元组,时间,随机数,os,sys


      
今日内容
collection模块
time与datetime模块
os模块
sys模块
random模块
序列化模块
json
pickle
subprocess模块(子进程)


1,collection模块
1》,具名元组 namedtuple ****
2》,队列 queue ****
3》,双端队列 deque
4》,有序字典 defaultdict

1,具名元组
from collections import namedtuple
point = namedtuple('坐标',['x','y','z']) # 第二个参数既可以传可迭代对象
point = namedtuple('坐标','x y z') # 也可以传字符串 但是字符串之间以空格隔开
p = point(1,2,5) # 注意元素的个数必须跟namedtuple第二个参数里面的值数量一致
print(p) # 坐标(x=1, y=2, z=5)
print(p.x) # 1
print(p.y) # 2
print(p.z) # 5
案列2:
city1 = namedtuple('日本','name person size')
# city = namedtuple('日本',['name ','person','hhj'])
city2 = namedtuple('扑克牌',['color','number','ba'])
c = city1('东京','吉老师','er') #日本(name='东京', person='吉老师', size='er')
print(c)
c2 = city2('东京','吉老师','er')
print(c2) #扑克牌(color='东京', number='吉老师', ba='er')

2,队列:先进先出(FIFO first in first out)
import queue
q = queue.Queue() # 生成队列对象
q.put('first') # 往队列中添加值
q.put('second')
q.put('third')
print(q.get()) # 从队列取值
print(q.get())
print(q.get())
print(q.get()) # 如果队列中的值取完了 程序会在原地等待 直到从队列中拿到值才停止

3,双端队列 deque
ps:队列不应该支持任意位置插值
只能在首尾插值(不能插队)
# 特殊点:双端队列可以根据索引在任意位置插值
from collections import deque

q = deque(['a',['b'],['c']])
print(q.append(1)) ### None
print(q.pop()) # 1
print(q) #deque(['海蛤壳j', 2, 'a', ['b'], ['c']])
print(q.popleft()) #海蛤壳j
print(q.popleft()) # 2
4,有序字典:怎么创建的顺序就是怎么样的(创建顺序有关)
from collections import OrderedDict
old = OrderedDict()
old['1']='111' 第一个键值对
old['y'] = 'ee'
old['z'] = '333'
print(old)
for i in old:
print(i)
5,Counter 计数(键值对形式存在)
from collections import Counter
s = 'abcdeabcdabcaba'
res = Counter(s)
print(res) #Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
2,时间模块:
三种表现形式
1.时间戳 *****
2.格式化时间(用来展示给人看的)
3.结构化时间
ps:时间戳不能直接转换为格式化时间,必须先转换为结构化时间,再转换为格式化时间
1,时间戳 import time
print(time.time()) # 时间戳 秒数
print(time.strftime('%Y-%m-%d %X')) # 年月日,时分秒
print(time.sleep(1))
print(time.strftime('%Y-%m-%d %H:%M:%S')) # 年月日,时分秒
print(time.strftime('%H:%M')) # 时分
print(time.strftime('%Y/%m')) # 年 月
3,结构化时间
print(time.localtime())
print(time.localtime(time.time()))
res = time.localtime(time.time())
# print(time.time())
print(time.mktime(res))
print(time.strftime('%Y-%m',time.localtime()))
print(time.strptime(time.strftime('%Y-%m',time.localtime()),'%Y-%m'))
import datetime
print(datetime.date.today()) # date>>>:年月日
print(datetime.datetime.today()) # datetime>>>:年月日 时分秒
res = datetime.date.today()
res1 = datetime.datetime.today()
print(res.year)
print(res.month)
print(res.day)
print(res.weekday()) # 0-6表示星期 0表示周一
print(res.isoweekday()) # 1-7表示星期 7就是周日
(******)
日期对象 = 日期对象 +/- timedelta对象
timedelta对象 = 日期对象 +/- 日期对象
current_time = datetime.date.today() # 日期对象
timetel_t = datetime.timedelta(days=7) # timedelta对象
res1 = current_time+timetel_t # 日期对象

print(current_time - timetel_t)
print(res1-current_time)
# UTC时间 (差距8个小时)
dt_today = datetime.datetime.today()
dt_now = datetime.datetime.now()
dt_utcnow = datetime.datetime.utcnow()
print(dt_utcnow,dt_now,dt_today)
3 # 随机模块*****
import random

print(random.randint(1,6)) # 随机取一个你提供的整数范围内的数字 包含首尾
print(random.random()) # 随机取0-1之间小数
print(random.choice([1,2,3,4,5,6])) # 摇号 随机从列表中取一个元素
res = [1,2,3,4,5,6]
random.shuffle(res) # 洗牌
print(res)
案例:
大写字母 小写字母 数字
5位数的随机验证码
chr
random.choice
封装成一个函数,用户想生成几位就生成几位

def get_code(n):
# 随机字符串为空
code = ''
for i in range(n): #循环5次
#先生成随机的大写字母 小写字母 数字
upper_str = chr(random.randint(65, 90))
lower_str = chr(random.randint(97, 122))
random_int = str(random.randint(0, 9))
#从上面三个中随机选择一个作为随机验证码的某一位
code += random.choice([upper_str, lower_str, random_int])
return code # 返回随机抽到的数字

res = get_code(5)
print(res) # 得到随机的5个字符的一个字符串
4,os模块:跟操作系统打交道的模块
      
今日内容
collection模块
time与datetime模块
os模块
sys模块
random模块
序列化模块
json
pickle
subprocess模块(子进程)


1,collection模块
1》,具名元组 namedtuple ****
2》,队列 queue ****
3》,双端队列 deque
4》,有序字典 defaultdict

1,具名元组
from collections import namedtuple
point = namedtuple('坐标',['x','y','z']) # 第二个参数既可以传可迭代对象
point = namedtuple('坐标','x y z') # 也可以传字符串 但是字符串之间以空格隔开
p = point(1,2,5) # 注意元素的个数必须跟namedtuple第二个参数里面的值数量一致
print(p) # 坐标(x=1, y=2, z=5)
print(p.x) # 1
print(p.y) # 2
print(p.z) # 5
案列2:
city1 = namedtuple('日本','name person size')
# city = namedtuple('日本',['name ','person','hhj'])
city2 = namedtuple('扑克牌',['color','number','ba'])
c = city1('东京','吉老师','er') #日本(name='东京', person='吉老师', size='er')
print(c)
c2 = city2('东京','吉老师','er')
print(c2) #扑克牌(color='东京', number='吉老师', ba='er')

2,队列:先进先出(FIFO first in first out)
import queue
q = queue.Queue() # 生成队列对象
q.put('first') # 往队列中添加值
q.put('second')
q.put('third')
print(q.get()) # 从队列取值
print(q.get())
print(q.get())
print(q.get()) # 如果队列中的值取完了 程序会在原地等待 直到从队列中拿到值才停止

3,双端队列 deque
ps:队列不应该支持任意位置插值
只能在首尾插值(不能插队)
# 特殊点:双端队列可以根据索引在任意位置插值
from collections import deque

q = deque(['a',['b'],['c']])
print(q.append(1)) ### None
print(q.pop()) # 1
print(q) #deque(['海蛤壳j', 2, 'a', ['b'], ['c']])
print(q.popleft()) #海蛤壳j
print(q.popleft()) # 2
4,有序字典:怎么创建的顺序就是怎么样的(创建顺序有关)
from collections import OrderedDict
old = OrderedDict()
old['1']='111' 第一个键值对
old['y'] = 'ee'
old['z'] = '333'
print(old)
for i in old:
print(i)
5,Counter 计数(键值对形式存在)
from collections import Counter
s = 'abcdeabcdabcaba'
res = Counter(s)
print(res) #Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})
2,时间模块:
三种表现形式
1.时间戳 *****
2.格式化时间(用来展示给人看的)
3.结构化时间
ps:时间戳不能直接转换为格式化时间,必须先转换为结构化时间,再转换为格式化时间
1,时间戳 import time
print(time.time()) # 时间戳 秒数
print(time.strftime('%Y-%m-%d %X')) # 年月日,时分秒
print(time.sleep(1))
print(time.strftime('%Y-%m-%d %H:%M:%S')) # 年月日,时分秒
print(time.strftime('%H:%M')) # 时分
print(time.strftime('%Y/%m')) # 年 月
3,结构化时间
print(time.localtime())
print(time.localtime(time.time()))
res = time.localtime(time.time())
# print(time.time())
print(time.mktime(res))
print(time.strftime('%Y-%m',time.localtime()))
print(time.strptime(time.strftime('%Y-%m',time.localtime()),'%Y-%m'))
import datetime
print(datetime.date.today()) # date>>>:年月日
print(datetime.datetime.today()) # datetime>>>:年月日 时分秒
res = datetime.date.today()
res1 = datetime.datetime.today()
print(res.year)
print(res.month)
print(res.day)
print(res.weekday()) # 0-6表示星期 0表示周一
print(res.isoweekday()) # 1-7表示星期 7就是周日
(******)
日期对象 = 日期对象 +/- timedelta对象
timedelta对象 = 日期对象 +/- 日期对象
current_time = datetime.date.today() # 日期对象
timetel_t = datetime.timedelta(days=7) # timedelta对象
res1 = current_time+timetel_t # 日期对象

print(current_time - timetel_t)
print(res1-current_time)
# UTC时间 (差距8个小时)
dt_today = datetime.datetime.today()
dt_now = datetime.datetime.now()
dt_utcnow = datetime.datetime.utcnow()
print(dt_utcnow,dt_now,dt_today)
3 # 随机模块*****
import random

print(random.randint(1,6)) # 随机取一个你提供的整数范围内的数字 包含首尾
print(random.random()) # 随机取0-1之间小数
print(random.choice([1,2,3,4,5,6])) # 摇号 随机从列表中取一个元素
res = [1,2,3,4,5,6]
random.shuffle(res) # 洗牌
print(res)
案例:
大写字母 小写字母 数字
5位数的随机验证码
chr
random.choice
封装成一个函数,用户想生成几位就生成几位

def get_code(n):
# 随机字符串为空
code = ''
for i in range(n): #循环5次
#先生成随机的大写字母 小写字母 数字
upper_str = chr(random.randint(65, 90))
lower_str = chr(random.randint(97, 122))
random_int = str(random.randint(0, 9))
#从上面三个中随机选择一个作为随机验证码的某一位
code += random.choice([upper_str, lower_str, random_int])
return code # 返回随机抽到的数字

res = get_code(5)
print(res) # 得到随机的5个字符的一个字符串
4,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的大小
5.sys模块:跟python解释器打交道模块
sys.argv           命令行参数List,第一个元素是程序本身路径 *******
sys.exit(n)        退出程序,正常退出时exit(0),错误退出sys.exit(1)
sys.version        获取Python解释程序的版本信息
sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 *****
sys.platform       返回操作系统平台名称










猜你喜欢

转载自www.cnblogs.com/Fzhiyuan/p/11210344.html