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