问题7:如何实现用户的历史记录功能(最多n条)

时间:2023-03-09 06:32:02
问题7:如何实现用户的历史记录功能(最多n条)

实例:制作猜字游戏,添加历史记录功能,显示用户最近猜过的数字

解决方案:使用容量为n的队列存储历史记录

  1. 使用标准库colections中的deque,一个双端循环队列
  2. 程序退出前,可以使用pickle将队列对象存入文件,再次运行程序时将导入其中

deque(序列, n):生成一个容量为n的序列,当序列中存储第n+1个数据时,则从左/右将溢出一个数;

pickle.dump(python对象, 文件名, 文件权限):创建一个文件,并将一个python对象存储其中;

from collections import deque
from random import randint
import pickle 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文件内的历史记录;