1.7 实现用户的历史记录功能

实际案例

我们制作了一个简单的猜数字的小游戏,现在,要为它添加历史记录功能,显示用户最近猜过的数字,应该如何实现?

游戏如下:

from random import randint

N = randint(0, 100)

def guess(k):
    if k == N:
        print 'You are 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 = raw_input("please input a number:")
    if line.isdigit():
        k = int(line)
        if guess(k):
            break

现在为其加一个功能,只显示最近5次的历史记录,应该如何实现?

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

我们可以使用 python 标准库collections中的deque,它是一个双端循环队列。

from collections import deque

q = deque([], 5)

q.append(1)
q.append(2)
q.append(3)
q.append(4)
q.append(5)
# q: [1,2,3,4,5]

q.append(6)
# q: [2,3,4,5,6]

回到之前的游戏中去,对代码进行修改。

from random import randint
from collections import deque

N = randint(0, 100)
history = deque([], 5)

def guess(k):
    if k == N:
        print 'You are 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 = 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)

相对来说,这是比较简单的问题。

但是,如果想要在程序关闭后再次打开,依然可以获取用户之前的历史记录,应该如何实现呢?我们在程序退出前,可以使用pickle将队列对象存入文件(dump),再次运行程序时将其导入(load)即可。

import pickle
from collections import deque
history = deque([], 5)

pickle.dump(history, open('history', 'w'))
history2 = pickle.load(open('history'))

results matching ""

    No results matching ""