py编程技巧-1.7-如何实现用户历史记录保存(最多n条)

实际案例:

很多应用程序都自带一个浏览用户的历史记录的功能
例如:

  • 浏览器历史记录
  • 视频播放历史记录
  • shell查看用户输入过的命令

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

解决方案:

使用容量为n的队列来存储历史记录

  • 使用标准库collections中的deque,他是一个双端循环队列
  • 程序退出前,可以使用pickie将队列对象存入文件,再次运行时程序将其导入
猜数小游戏:
from random import randint

Num = randint(0,100)

def guess(k):
    if k == Num:
        print "success"
        return True
    elif k > Num:
        print "the number is bigger"
    else:
        print "the number is smaller"
    return False

while True:
    line = raw_input("please input a number(1~100)")
    # line是一个字符串,通过isdigit()方法来看这个字符串是不是一个数字
    if line.isdigit():
        k = int(line)
        if guess(k):
            break
队列小例子:
# 使用队列

from collections import deque

# deque传入两个参数:1.初始值;2.队列长度
q = deque([],5)

# append方法从右部添加
q.append(1)
q.append(2)
q.append(3)
q.append(4)
q.append(5)
q.append(6)

print q
加上了历史记录的猜数字小游戏:
from collections import deque
from random import randint

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

def guess(k):
    if k == Num:
        print "success"
        return True
    elif k > Num:
        print "the number is bigger"
    else:
        print "the number is smaller"
    return False

while True:
    line = raw_input("please input a number(1~100):")
    if line.isdigit():
        k = int(line)
        history.append(k)
        if guess(k):
            break
    elif line == 'history' or line == 'h?':
        print list(history)
    else:
        print 'input error'
将对象存储进文件进行持久化
import pickle
from collections import deque
q = deque([3,4,5,6,7])
# dump()方法传入两个参数: 1.一个是要保存的对象;2.一个可写的文件对象
pickle.dump(q,open('history','w'))
q2 = pickle.load(open('history'))
print q2
cmd乱码修改

chcp 936 #utf-8输出

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值