1、collections
append 和 pop、popleft
from collections import deque
dq = deque() # 可以直接传参
dq.append('a')
dq.append('b')
dq.appendleft('c')
print(dq.popleft())
from collections import OrderedDict
od = OrderedDict([('a', [1,2,3,4]), ('b', 2), ('c', 3)])
for k in od:
print(k,od[k])
# ##结果:a [1, 2, 3, 4]
# b 2
# c 3
l = [11,22,33,44,55,66,77,88,99,90]
dic = {}
for i in l:
if i > 66:
if 'k1' in dic:
dic['k1'].append(i)
else:
dic['k1'] = []
dic['k1'].append(i)
elif i<66:
if 'k2' in dic:
dic['k2'].append(i)
else:
dic['k2'] = []
dic['k2'].append(i)
print(dic)
lis = '11,22,33,44,55,66,77,88,99,90'
from collections import defaultdict
dic = defaultdict(list)
for i in lis:
if i < 66:
dic['key1'].append(i)
else:
dic['key2'].append(i)
print(dic)
from collections import defaultdict
def func():
return 0
my_dict = defaultdict(func)
# my_dict = {}
print(my_dict['k'])
2、queue
import queue #队列_多线程多进程
q = queue.Queue()
q.put([1])
q.put(2) #处理任务
q.put('aaa')
# print(q.qsize())
print(q.get())
print(q.get())
print(q.get()) #hold住的功能
print(q.qsize())
print(q.get_nowait()) #如果没有不会hold住,且会报错
from collections import deque
dq = deque()
dq.append('a')
dq.append('b')
dq.appendleft('c')
print(dq.popleft())
3、sys
import sys
args_lst = sys.argv #['6sys.py', 'alex', '3714']
if len(args_lst) ==3 and args_lst[1] == 'alex' and args_lst[2] == '3714':
print('执行程序了')
else:
sys.exit()
4、time时间:时间戳 字符串 结构化时间1、一个重要的大程序:tamp_old = time.mktime(time.strptime('2017-11-11 11:30:00','%Y-%m-%d %H:%M:%S')) tamp_new = time.mktime(time.strptime('2017-11-12 10:00:06','%Y-%m-%d %H:%M:%S')) tamp_c = tamp_new-tamp_old struct_time = time.gmtime(tamp_c) print('过了%d年%d月%d天%d时%d分%d秒'%(struct_time.tm_year-1970,struct_time.tm_mon-1, struct_time.tm_mday-1,struct_time.tm_hour, struct_time.tm_min,struct_time.tm_sec))
2、其他print(time.time()) #时间戳:记录了从1970.1.1到现在的所有秒time.sleep(1)ret = time.strftime('%Y-%m-%d %a %H:%M:%S') #string format timeprint(ret)print(time.localtime()) # 北京时间print(time.gmtime()) # 伦敦时间print(time.time())1000000000ret = time.localtime(3000000000)print(ret)print(time.mktime(ret))ret2 = time.strftime('%c',ret)print(ret2)print(time.strptime('1990-3-31','%Y-%m-%d'))print(time.mktime(time.strptime('1990-3-31','%Y-%m-%d')))print(time.asctime())99print(time.asctime(time.localtime(1000000)))print(time.ctime(1000000)) # Mon Jan 12 21:46:40 1970
5、序列化
什么叫做序列化字符串 列表 字典 元组字典和列表 不能写到文件里{[]} ==str==str({[]})str({[]}) ==eval('')s_dic =str({'k':'v'})pint(repr(s_dic))print(repr(eval(s_dic)),type(eval(s_dic)))序列化方法格式转换把python中的数据转换成str —— 序列化可以str转换成python的数据 —— 反序列化序列化 json ***** pickle **** shelve ***json : 所有语言通用,能转换的数据类型有限 *****pickle : 只限于python,能转换所有的数据类型 做游戏的时候shelve : 只限于python语言,能转换所有的数据类型, 使用方法类似字典一、jsonimport json①ret = json.dumps({'k':(1,2,3)})# dumps就是将一个东西变成字符串print(repr(ret),type(ret))# '{"k": [1, 2, 3]}' <class 'str'>②ret2 = json.loads(ret) # loads就是将字符串转换回原来的东西print(repr(ret2),type(ret2))# {'k': [1, 2, 3]} <class 'dict'>③f = open('json_file','a')json.dump({'k':'v'},f)# 文件里的内容 {"k": "v"}f.close()④withopen('json_file')as fret = json.load(f)print(ret,type(ret))# {'k': 'v'} <class 'dict'>⑤===================================↓↓↓这些看不懂for linein f:json.loads(line)str = json.dumps(dict)f.write(str+'\n')============================================↑↑二、pickle(Python特有的)****dumps / loads / dump / loadpickle ---- 序列化任何数据类型,python专有的不能和其他语言兼容,结果是bytesimport pickle#用pickle序列化的数据,反序列化也必须用pickleret = pickle.dumps({1,2,3,4})print(ret)三、shelve***①shelve 只提供一个open,shelve.open('文件名')拿到一个文件句柄,这个文件句柄就可以当做字典操作②正常情况下shelve打开的文件句柄感知不到值的修改,设置writeback = True就可以保存修改内容了③正常情况下不支持多个人同时写,支持多个人同时读,如果只是读的化,就设置flag='r'1、importshelve①f = shelve.open('shelve_file') f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'} #直接对文件句柄操作,就可以存入数据 f.close()
②f1 = shelve.open('shelve_file') existing = f1['key'] #取出数据的时候也只需要直接用key获取即可,但是如果key不存在会报错 f1.close() print(existing)
不支持多个人同时写,支持多个人同时读,如果只是读的化,就设置flag='r'③f = shelve.open('shelve_file',flag='r') f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'} #直接对文件句柄操作,就可以存入数据 f.close()
④f1 = shelve.open('shelve_file') print(f1['key']) f1['key']['new_value'] = 'this was not here before' #改 f1.close()## 并没有改的内容 {'int': 10, 'float': 9.5, 'string': 'Sample data'}
⑤f = shelve.open('shelve_file',flag='r') print(f['key']) # {'int': 10, 'float': 9.5, 'string': 'Sample data'} f.close()
⑥正常情况下shelve打开的文件句柄感知不到值的修改,设置 writeback = True就可以保存修改内容了f2 = shelve.open('shelve_file', writeback=True) print(f2['key']) f2['key']['new_value'] = {1,2,3} print(f2['key']) # {'int':10,'float':9.5,'string':'Sample data','new_value':{1,2,3}} f2.close()
⑦f = shelve.open('shelve_file',flag='r') print(f['key']) f.close()
6、os 操作系统相关 *****
importos和系统路径有关的print(os.getcwd()) # 当前目录 D:\sunv_lx\month2\week5 os.chdir(r'D:\sunv_lx') print(os.getcwd()) # D:\sunv_lx print(os.curdir) # . print(os.pardir) # ..
和系统文件夹和文件相关的os.mkdir('dir1') # 在 week5 下新建了一个 Directory 名为 dir1 os.makedirs('dir3\\dir4') # 在 week5 下新建了一个 Directory 名为 dir3 下级又建了一个dir4 os.rmdir('dir3\\dir4') # 删除dir3 下的dir4 os.removedirs('dir3\\dir4') # 删除dir3 下的dir4 ,如果dir3 也为空 则 一起删除 os.remove('文件路径') # ??? os.rename('文件路径') # ??? print(os.listdir(r'D:\sunv_lx\month2\week5')) # ['move_info7', '正则day19(1113).py', '爬虫.py'] 看当前的目录
=============================#这块操作系统不懂↓↓↓↓↓和操作系统特征相关的print(os.stat(r'D:\sunv_lx\month2\week5\正则day19(1113).py')) # 一大串 类似 st_dev=958456, st_nlink=1, print(os.sep) #/user/bin/ # 这个不太懂 结果是 / 拼目录 C:\Python36\python\nihaohahaha C:\Python36\Scripts\;C:\Python36\ print(os.environ)
===========================================和操作系统的命令相关—— dircdos.system('dir') #没有返回值,且直接执行代码,把结果直接输出 ret = os.popen('dir') #如果有结果就将结果返回回来 print(ret.read()) #ret.read()获取结果 os.path os.path(当然了,每一个ret下面要 print一下) ret = os.path.split(r'D:\sunv_lx\month2\week5\正则day19(1113).py')# 将文件和 目录分开 # ##('D:\\sunv_lx\\month2\\week5', '正则day19(1113).py') ret = os.path.basename(r'D:\sunv_lx\month2\week5') # week5 # 只留下最后一个目录 ret = os.path.basename(r'D:\sunv_lx\month2\week5\正则day19(1113).py') # week5 # 只留下最后一个目录 ret = os.path.isfile(r'C:\Users\Administrator\PycharmProjects\全栈s8') # False ret = os.path.isfile(r'D:\sunv_lx\month2\week5') # False ret = os.path.isfile(r'D:\sunv_lx\month2\week5\正则day19(1113).py') # True print(ret)
7、random 随机数相关***
1、一个重要程序:生成6位字母数字随机密码lis = [] for i in range(6): ret1 = str(random.randint(0,9)) # 注意 str ret2 = chr(random.randint(65,90)) # 注意 chr ret3 = chr(random.randint(97,122)) # 注意 chr choice = random.choice([ret1,ret2,ret3]) # 注意[ ] l.append(choice) print(''.join(lis))
2、①生成随机整数print(random.randint(1,2))#必须是两个参数,规定一个范围 [1,2] print(random.randrange(100)) #一个参数 print(random.randrange(1,2)) #两个个参数 [1,2) print(random.randrange(90,100,2)) #三个参数,最后一个是步长
②从一个序列中随机选择:一个 choice,多个 sampleprint(random.choice('abc'))print(random.sample([1,'23',[4,5]],2))③打乱一个序列的顺序item=[1,3,5,7,9]random.shuffle(item)#改变了原列表print(item)
8、异常处理 *****
2+''#TypeError错误1/0#ZeroDivisionError错误iter([]).next()#AttributeError 错误iter([]).__next__()#StopIteration 异常import hahaha#ModuleNotFoundError[][4]#IndexError2、try: a=1 except NameError: print('NameError') print(123) try: num = int(input('请输入序号 : ')) # print(num) # 1/0 except ValueError as e: print('出错啦',e) except Exception as e: print('') try except语句
3、需要检测异常的代码放在try代码块需要处理的代码放在except代码块不报错不执行except内的代码,except处理的错误名称应该和实际报错一致,否则无效如果报错try中报错之后的代码不执行不影响try外面的代码except ErrorNameas 变量名:变量名中存储的就是错误的具体提示except支持多分支处理的方式,从上到下先找到能处理的error类型,就执行该except中的内容万能异常 exceptException as e,e表示错误提示,应该放在所有except之后对于你已经预料到的错误 应该使用指定的异常进行特殊处理万能异常是用来处理预料不到的异常类型的4、①try: num = int(input('请输入序号 : ')) except Exception as e: print('异常啦') else: #如果try中的代码不会发生异常,就走这个else中的内容 print('可以的')
②try: num = int(input('请输入序号 : ')) except Exception as e: print('异常啦') else: #如果try中的代码不会发生异常,就走这个else中的内容 print('可以的') finally: print('不管异常不异常我都走这个')
③
def func(): f = open('f','w') try: for i in range(10): f.write(i) except Exception: print(123) return finally: #在一个函数中 操作一个文件 需要关闭,在finally中关闭 print('before close') f.close() print('after close') func()
二、异常处理:不要!!!在大段代码外面加*********像这样(no):def main():func()func()try:main()except Exception:pass