zoukankan      html  css  js  c++  java
  • Python:如何实现用户的历史记录功能(最多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文件内的历史记录;
  • 相关阅读:
    5月29 流程
    5月27 权限设置及功能
    5月26 留言板练习题
    5月24 文件操作
    5月23 文件上传及图片上传预览
    5月23 注册审核
    5月21 回话控制SESSION COOKIE
    5月21 汽车查询及批量删除----php方法
    5月21 练习AJAX的查看详细及批量删除
    5月20 三级联动
  • 原文地址:https://www.cnblogs.com/volcao/p/8728612.html
Copyright © 2011-2022 走看看