在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个额外的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等。python
git
shell
from collections import namedtuple point = namedtuple('坐标',['x','y','z']) #也能够下面格式 point1 = namedtuple('坐标','x, z, y') # 第二个参数既能够为可迭代对象,也能够是字符串 # 字符串得用空格隔开 p = point(1,2,3) # 注意元素的个数必须和nametype第二个参数的数量一致 print(p) print(p.x) print(p.y) print(p.z)
扑克牌json
from collections import namedtuple card= namedtuple('扑克牌','color,number') # card= namedtuple('扑克牌',['color,number']) A = card('♥','A') print(A) print(A.color) print(A.number)
城市天气bash
city = namedtuple('中国','city,weather,temperature') c = city('北京','晴','30') print(c) print(c.city) print(c.weather) print(c.temperature)
网络
数据结构
队列:先进先出, 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())
deque双端队列app
from collections import deque q = deque(['a','b','c']) # 添加值 q.append('1') # 左添加值 q.appendleft('2') print(q) # 取值 print(q.pop()) #取左值 #特殊点 能够根据索引在任意位置插入值 q.insert(2,'哈哈') q.insert(4,'嘿嘿')
队列不该该支持在任意位置插入值,只能在首尾插值dom
语法ide
插入
insert
添加
append
appendleft
取值
pop
popleft
normal_d = dict([('a',1),('b',2),('c',3)]) print(normal_d) normal_d['q'] = 11 normal_d['w'] = 22 print(normal_d)
有序字典
from collections import OrderedDict order_d = OrderedDict([('a',1),('b',2),('c',3)]) print(order_d) order_d1 = OrderedDict() order_d1['x'] = 11 order_d1['y'] = 22 order_d1['z'] = 33 print(order_d1) for i in order_d1: print(i)
OrderedDict的Key会按照插入的顺序排列,不是Key自己排序
value = [11,22,33,44,55,66,77,88,99] 将全部大于 66` `的值保存至字典的第一个'key'中,将小于 66` `的值保存至第二个'key'的值中。 values = [11, 22, 33,44,55,66,77,88,99,90] my_dict = {} for value in values: if value>66: if my_dict.has_key('k1'): my_dict['k1'].append(value) else: my_dict['k1'] = [value] else: if my_dict.has_key('k2'): my_dict['k2'].append(value) else: my_dict['k2'] = [value]
使用模块
from collections import defaultdict values = [11, 22, 33,44,55,66,77,88,99,90] my_dict = defaultdict(list) # 后续该字典中新建的key对应的value默认就是列表 print(my_dict['aaa']) for value in values: if value>66: my_dict['k1'].append(value) else: my_dict['k2'].append(value) print(my_dict) my_dict1 = defaultdict(int) print(my_dict1['xxx']) print(my_dict1['yyy']) my_dict2 = defaultdict(bool) print(my_dict2['kkk']) my_dict3 = defaultdict(tuple) print(my_dict3['mmm'])
使用'dict'时,若是引用的'Key'不存在,就会抛出'KeyError'。若是但愿'key'不存在时,返回一个默认值,就能够用'defaultdict'
>>> from collections import defaultdict >>> dd = defaultdict(lambda: 'N/A') >>> dd['key1'] = 'abc' >>> dd['key1'] # key1存在 'abc' >>> dd['key2'] # key2不存在,返回默认值 'N/A'
s = 'asdfghjkhgfdsawssadfghjhhfgdsdsdag' a = {} for i in s: print(i) a[i] = 0 # 在就加1 print(a)
使用模块
from collections import Counter s = 'asdfghjkhgfdsawssadfghjhhfgdsdsdag' a = {} res = Counter(s) print(Counter) print(res) # 获得了v值 for q in res.values(): print(q)
表现时间的三种方式 1.时间戳(timestamp) 2.格式化时间(format string) 3.结构化时间(struct_time)
%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 当前时区的名称 %% %号自己
import time 时间戳 time.time() 格式化时间 print(time.strftime('%Y-%m-%d')) print(time.strftime('%Y-%m-%d %H:%M:%S')) print(time.strftime('%Y-%m-%d %X')) # %X等价于%H:%M:%S 时间元组 localtime将一个时间戳转换为当前时区的struct_time time.localtime()
时间戳是计算机可以识别的时间;时间字符串是人可以看懂的时间;元组则是用来操做时间的
转换时间
时间戳-->结构化时间 time.gmtime(时间戳) time.localtime(时间戳) >>>time.gmtime(1500000000) 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.localtime(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.mktime(结构化时间) >>>time_tuple = time.localtime(1500000000) >>>time.mktime(time_tuple) 1500000000.0
结构化时间-->字符串时间 time.strftime("格式定义","结构化时间") 结构化时间参数若不传,则显示当前时间 >>>time.strftime("%Y-%m-%d %X") '2017-07-24 14:55:36' >>>time.strftime("%Y-%m-%d",time.localtime(1500000000)) '2017-07-14'
字符串时间-->结构化时间 time.strptime(时间字符串,字符串对应格式) >>>time.strptime("2017-03-16","%Y-%m-%d") time.struct_time(tm_year=2017, tm_mon=3, tm_mday=16, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=75, tm_isdst=-1) >>>time.strptime("07/24/2017","%m/%d/%Y") time.struct_time(tm_year=2017, tm_mon=7, tm_mday=24, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=205, tm_isdst=-1)
结构化时间 --> %a %b %d %H:%M:%S %Y串 time.asctime(结构化时间) 若是不传参数,直接返回当前时间的格式化串 >>>time.asctime(time.localtime(1500000000)) 'Fri Jul 14 10:40:00 2017' >>>time.asctime() 'Mon Jul 24 15:18:33 2017' 时间戳 --> %a %b %d %H:%M:%S %Y串 time.ctime(时间戳) 若是不传参数,直接返回当前时间的格式化串 >>>time.ctime() 'Mon Jul 24 15:19:07 2017' >>>time.ctime(1500000000) 'Fri Jul 14 10:40:00 2017'
import datetime print(datetime.date.today()) # date>>>:年月日 print(datetime.datetime.today()) # datetime>>>:年月日 时分秒
import 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) print(timetel_t) print(res1) # - print(current_time - timetel_t) print(res1-current_time)
小练习 计算今天距离今年过生日还有多少天
birth = datetime.datetime(2019,12,21,8,8,8) current_time = datetime.datetime.today() print(birth-current_time)
# UTC时间 dt_today = datetime.datetime.today() dt_now = datetime.datetime.now() dt_utcnow = datetime.datetime.utcnow() print(dt_utcnow,dt_now,dt_today)
import random 整数 random.randint(1,10) # 随机取一个数字 random.randrange(1,10,2) # 大于等于1且小于10之间的奇数 小数 random.random() # 随机取0-1的小数 random.uniform(1,3) #大于1小于3的小数 随机选择值返回 random.choice([1, 2, 3, 4, 5, 6,7]) # 随机从列表取值 random.sample([1,'2',[3,4]],9) # #列表元素任意2个组合
res = [1, 2, 3, 4, 5, 6,7] random.shuffle(res) print(res)
随机验证码
大写字母 小写字母 数字
5位数的随机验证码
chr
random.choice
封装成一个函数,用户想生成几位就生成几位
def get_code(n): code = '' for i in range(n): # 先生成随机的大写字母 小写字母 数字 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(4) print(res)
import os listdir 会将当前文件夹的文件展现出来 os.mkdir 自动建立文件夹 os.path.exists 判断文件夹是否存在 os.path.isfile 只能判断文件是否存在,不能判断文件夹 remove 删除文件 os.rmdir 删除单级目录,只能删除空文件夹 os.getcwd() 获取目录 os.chdir() 切换当前所在目录 os.path.getsize() 获取文件大小 大小单位为字节
语法
os.getcwd() 获取当前工做目录,即当前python脚本工做的目录路径 os.chdir("dirname") 改变当前脚本工做目录;至关于shell下cd os.curdir 返回当前目录: ('.') os.pardir 获取当前目录的父目录字符串名:('..') 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.sep 输出操做系统特定的路径分隔符,win下为"\\",Linux下为"/" os.linesep 输出当前平台使用的行终止符,win下为"\t\n",Linux下为"\n" os.pathsep 输出用于分割文件路径的字符串 win下为;,Linux下为: os.name 输出字符串指示当前使用平台。win->'nt'; Linux->'posix' os.system("bash command") 运行shell命令,直接显示 os.environ 获取系统环境变量 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的大小
练习
选择文件查看
文件夹
火影人物
鸣人.txt
向日宁次.txt
卡卡西.txt
我爱罗.txt
大蛇丸.txt
波佐助.txt
import os BASE_DIR = os.path.dirname(__file__) MOVIE_DIR = os.path.join(BASE_DIR,'火影人物') movie_list = os.listdir(MOVIE_DIR) while True: for i,j in enumerate(movie_list,1): print(i,j) choice = input('你想看谁的啊(小姑娘/小伙子)>>>:').strip() if choice.isdigit(): # 判断用户输入的是不是纯数字 choice = int(choice) # 传成int类型 if choice in range(1,len(movie_list)+1): # 判断是否在列表元素个数范围内 # 获取用户想要看的文件名 target_file = movie_list[choice-1] # 拼接文件绝对路径 target_path = os.path.join(MOVIE_DIR,target_file) with open(target_path,'r',encoding='utf-8') as f: print(f.read()) else: print('所选不在名单中') else: print('输入数字哦')
sys.argv 命令行参数List,第一个元素是程序自己路径 sys.exit(n) 退出程序,正常退出时exit(0),错误退出sys.exit(1) sys.version 获取Python解释程序的版本信息 sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 sys.platform 返回操做系统平台名称
mport sys # sys.path.append() # 将某个路径添加到系统的环境变量中 # print(sys.platform) # print(sys.version) # python解释器的版本 print(sys.argv) # 命令行启动文件 能够作身份的验证 if len(sys.argv) <= 1: print('请输入用户名和密码') else: username = sys.argv[1] password = sys.argv[2] if username == 'jason' and password == '123': print('欢迎使用') # 当前这个py文件逻辑代码 else: print('用户不存在 没法执行当前文件')
序列化: 序列:字符串 序列化:其它数据类型转换成字符串的过程 写入文件的数据必须是字符串 基于网络传输的数据必须是二进制 序列化:其余数据类型转换成字符穿的过程 反序列化:字符串转换成其余数据类型
目的:
一、以某种存储形式使自定义[对象持久化](https://baike.baidu.com/item/%E5%AF%B9%E8%B1%A1%E6%8C%81%E4%B9%85%E5%8C%96); 二、将对象从一个地方传递到另外一个地方。 三、使程序更具维护性。
json模块 全部的语言都支持json格式 支持的数据类型不多 字符串 列表 字典 整型 元组(转成列表) 布尔值 pickle模块 只支持python python全部的数据类型都支持 json,用于字符串 和 python数据类型间进行转换 pickle,用于python特有的类型 和 python的数据类型间进行转换
json.dumps() 序列化 将其余数据类型转换成json格式的字符串 json.dump() dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件 json.loads() 反序列化 将json格式的字符串转换成其余数据类型 json.load() load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回 注意,json转换完的字符串类型的字典中的字符串是由""表示的
d = {"name":"jason"} print(d) #序列化:将一个字典转换成一个字符串 res = json.dumps(d) # json格式的字符串 必须是双引号 >>>: '{"name": "jason"}' print(res,type(res)) #反序列化:将一个字符串格式的字典转换成一个字典 res1 = json.loads(res) print(res1,type(res1))
d = {"name":"jason"} with open('userinfo','w',encoding='utf-8') as f: json.dump(d,f) # 装字符串并自动写入文件 with open('userinfo','r',encoding='utf-8') as f: res = json.load(f) print(res,type(res)) with open('userinfo','r',encoding='utf-8') as f: res1 = json.load(f) # 不可以屡次反序列化 res2 = json.load(f) print(res1,type(res1)) print(res2,type(res2)) with open('userinfo','w',encoding='utf-8') as f: json_str = json.dumps(d) json_str1 = json.dumps(d) #换行写 f.write('%s\n'%json_str) f.write('%s\n'%json_str1) #换行读 with open('userinfo','r',encoding='utf-8') as f: for line in f: res = json.loads(line) print(res,type(res)) t = (1,2,3,4) print(json.dumps(t)) # fp = 文件句柄(对象) 在源码中fp =文件句柄(对象)
ensure_ascii 是否转码
有中文时,使用 d1 = {'name':'熊大'} print(json.dumps(d1,ensure_ascii=False))
dumps、dump(序列化,存)、 loads(反序列化,读)、load (不只能够序列化字典,列表...能够把python中任意的数据类型序列化)
import pickle d = {'name':'jason'} res = pickle.dumps(d) # 将对象直接转成二进制 print(pickle.dumps(d)) res1 = pickle.loads(res) print(res1,type(res1))
用pickle操做文件的时候 文件的打开模式必须是b模式
with open('userinfo_1','wb') as f: pickle.dump(d,f) with open('userinfo_1','rb') as f: res = pickle.load(f) print(res,type(res))
1.用户经过网络链接上了你的这台电脑 2.用户输入相应的命令 基于网络发送给了你这台电脑上某个程序 3.获取用户命令 里面subprocess执行该用户命令 4.将执行结果再基于网络发送给用户 这样就实现 用户远程操做你这台电脑的操做
import subprocess 执行系统指令 import os # dir 列出全部进程 os.system('dir') # 打开进程 # shell 命令解释器 # stdout 标准输出 # 指定输出管道 stdout=subprocess.PIPE a=subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE) # 从管道中读取出执行结果 #[1] 输出 a1=subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE ) print(a1.stdout.read().decode('GBK')) # [2] 输入 a1=subprocess.Popen('dir',shell=True,stdout=subprocess.PIPE,stdin= subprocess.PIPE) # PIPE 大写的单词为常量 # PIPE = -1 # STDOUT = -2 # DEVNULL = -3 # [3] 错误输出 print(a1.stderr .read().decode('utf-8')) # tasklist | findstr python # 先执行tasklist 把结果交给 findstr 来处理 把p1的输出传给p2, p1 = subprocess.Popen("tasklist",shell=True,stdout=subprocess.PIPE) p2 = subprocess.Popen('findstr QQ',shell=True,stdin=p1.stdout,stdout=subprocess.PIPE,stderr= subprocess.PIPE ) print(p2.stdout.read()) print(p2.stderr.read()) # 参数1 指令 # p = subprocess.Popen("你的指令或是某个exe",shell=True,stderr=,stdin=,stdout=) # 2 是不是一个指令 # 3 错误输出管道 # 4 输入管道 # 5 输出管道 # # 取出管道中的数据 # p.stderr.read() # p.stdout.read() # p.stdin.write(p.stdout.read())# # 将输入写入管道 交给对方进程