如何实现用户的历史记录功能
python备忘

我们写一个简单的猜数字小游戏
from random import randint N = randint(0,100) def guess(k): if k==N: print 'right' return True if k<N: print '%s is less-than N' %k else: print '%s is greater-than N' %k while True: line = raw_input("Please input a number:") if line.isdigit(): k = int(line) if guess(k): break
现在我们想把最近猜的那五个数字,做的历史记录保存起来,应该怎么做呢?我们可以使用队列来处理
from collections import deque import pickle q = deque([],5) q.append(1) q.append(2) q.append(3) q.append(4) q.append(5) q.append(6) print q
使用方法如上,创建一个空间为5的队列,空间满了的情况下,后进的会把先进的给挤出去。
但是现在历史纪录是存放在内存当中的,如果我们想要把它存在文件当中的时候,怎么操作呢?
我们可以使用pickle.dump(q,open('history','w')),把历史纪录存放在文件当中
可以使用pickle.load(open('history'))打开文件,读取历史纪录
我们修改一下啊猜数字程序的代码
from random import randint from collections import deque N = randint(0,100) history = deque([],5) def guess(k): if k==N: print 'right' return True if k<N: print '%s is less-than N' %k else: print '%s is greater-than N' %k while True: line = raw_input("Please input a number:") if line.isdigit(): k = int(line) history.append(k) if guess(k): break elif line == 'history' or line == 'h?': print list(history)
这样我们输入history的时候,就可以查看历史纪录了。