2-7实现用户的历史记录功能

# -*- coding:utf-8 -*-

from random import randint
from collections import deque
import pickle

# 问题描述:
# 所使用的deque(双循环队列)处理结果都存在内存当中,当再次运行程序将会消失


# 解决方案:
# 可以在程序推出前,使用pickle将队列对象存入文件,再次运行程序时将其导入
# pickle.dump(q, open('history', 'w'))
# q2 = pickle.load(open('history'))


N = randint(0, 100)
history = deque([], 5) # deque() 的第一个参数是初始值,第二个是size
history = pickle.load(open('history.txt'))

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 = raw_input('please input a number:')
    # 使用input和raw_input都可以读取控制台的输入,但是input和raw_input在处理数字时是有区别的
    # input返回的是数值类型,如int,float && 会计算字符串中的数字表达式
    # raw_inpout返回的是字符串类型,string类型

    if line.isdigit():         # 检测字符串是否只有数字组成
        k = int(line)          # 必须转化成int类型
        history.append(k)
        if guess(k):
            pickle.dump(history, open('history.txt', 'w'))
            break
    elif line == 'history' or line == 'h?':
        print list(history)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现搜索历史记录和去重、缓存,可以使用uni-app提供的本地存储功能。 首先,需要定义一个对象用来保存搜索历史记录,例如: ```javascript const history = { list: [], // 保存搜索历史的数组 maxLen: 10, // 最大历史记录数 add(keyword) { // 添加历史记录的方法 const index = this.list.indexOf(keyword) if (index !== -1) { this.list.splice(index, 1) // 如果已存在该记录则先删除 } this.list.unshift(keyword) // 添加到数组头部 if (this.list.length > this.maxLen) { this.list.pop() // 如果超过最大长度则删除末尾记录 } }, clear() { // 清空历史记录的方法 this.list = [] } } ``` 然后,可以在搜索框的输入事件中调用 add 方法,将搜索关键字添加到历史记录中。同时,在页面加载时可以从本地存储中读取历史记录,例如: ```javascript onLoad() { const historyList = uni.getStorageSync('history') || [] // 从本地存储中读取历史记录 history.list = historyList // 覆盖 history 对象的 list 属性 } ``` 为了防止用户重复添加同一条历史记录,可以在 add 方法中先通过 indexOf 方法判断该记录是否已存在,如果存在则先删除原有记录。 ```javascript add(keyword) { // 添加历史记录的方法 const index = this.list.indexOf(keyword) if (index !== -1) { this.list.splice(index, 1) // 如果已存在该记录则先删除 } this.list.unshift(keyword) // 添加到数组头部 if (this.list.length > this.maxLen) { this.list.pop() // 如果超过最大长度则删除末尾记录 } } ``` 最后,为了实现历史记录的缓存功能,可以在 add 和 clear 方法中调用 uni.setStorageSync 方法将历史记录保存到本地存储中,例如: ```javascript add(keyword) { // 添加历史记录的方法 // ... uni.setStorageSync('history', this.list) // 将历史记录保存到本地存储中 }, clear() { // 清空历史记录的方法 this.list = [] uni.setStorageSync('history', this.list) // 将清空后的历史记录保存到本地存储中 } ``` 这样就可以实现搜索历史记录和去重、缓存的功能了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值