如何实现用户的历史记录?
解决方案:使用容量为n的队列存储历史记录。
步骤:
- 使用collection中的deque,它是一个双向循环列表
- 退出前,使用pickle将队列中的对象存入文件,再次运行时将其导入。
#实现用户的历史记录功能,记录5条
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)
return False
while True:
line = 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))