如何实现用户的历史记录?
解决方案:使用容量为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))
本文介绍了一种使用Python的deque和pickle模块来实现用户历史记录的方法。通过限制deque的大小可以只保留最近的几条记录,并在程序退出时保存这些记录到文件中,在下次启动时再读取出来。
4490

被折叠的 条评论
为什么被折叠?



