問題7:如何實現用戶的歷史記錄功能(最多n條)
阿新 • • 發佈:2018-04-06
NPU app while less ase 退出 添加 數字 pri
實例:制作猜字遊戲,添加歷史記錄功能,顯示用戶最近猜過的數字
解決方案:使用容量為n的隊列存儲歷史記錄
- 使用標準庫colections中的deque,一個雙端循環隊列
- 程序退出前,可以使用pickle將隊列對象存入文件,再次運行程序時將導入其中
deque(序列, n):生成一個容量為n的序列,當序列中存儲第n+1個數據時,則從左/右將溢出一個數;
pickle.dump(python對象, 文件名, 文件權限):創建一個文件,並將一個python對象存儲其中;
from collections import deque from random import randint importpickle history = deque([], 5) a = randint(0, 20) def guss(b) if b == a: print(‘right‘) return True if b < a: print(‘%s is less-than a‘%b) else: print(‘%s is greater-than a‘%b) while True: b0 = input(‘please input a number:‘) if b0.isdigit() and b0 =! ‘history‘: b = b0 history.append(b) if guss(b): break pickle.dump(history, open(‘histoy‘, ‘w‘)) #將歷史記錄存儲值文件history; q = pickle.load(open(‘history‘)) #讀取history文件內的歷史記錄;
問題7:如何實現用戶的歷史記錄功能(最多n條)