实现用户的历史记录功能(1.5)



实现用户的历史记录功能

很多应用有历史记录的功能

  • 浏览器里最近访问页面
  • 视频播放器里 最近播放的视频
  • Shell查看以前用过的命令

注:下边1,2,3是方法,后边是一个其他的东西

1. 猜数字游戏

from random import randint
import time

def guess(temp_num, target):
    if temp_num == target:
        print("you are right!")
        return  True
    elif temp_num > target: 
        print("%d is greater than target" % temp_num)
    else:
        print("%d is less than target" % temp_num)
    return False

def guess_num_game():
    target = randint(0, 100)
    while 1:
        temp_num = input("please input a num: ")
        if temp_num.isdigit():
            temp_num = int(temp_num)
            if guess(temp_num, target):
                break

guess_num_game()

2 如何记录已经猜过的数字

from collections import deque

def guess_num_game2():
    target = randint(0, 100)
    history = deque([], 5)

    while 1:
        temp_num = input("please input a num: ")
        if temp_num.isdigit():
            temp_num = int(temp_num)
            history.append(temp_num)
            if guess(temp_num, target):
                break
        elif temp_num == '?':
            print(list(history))

guess_num_game2()

3. 如何写到文件里

from collections import deque
import pickle

def guess_num_game3():
    target = randint(0, 100)
    history = pickle.load(open('history', 'rb'))

    while 1:
        temp_num = input("please input a num: ")
        if temp_num.isdigit():
            temp_num = int(temp_num)
            history.append(temp_num)
            pickle.dump(history, open('history', 'wb'))
            if guess(temp_num, target):
                break
        elif temp_num == '?':
            history = pickle.load(open('history', 'rb'))
            print(list(history))

guess_num_game3()

说一下deque

deque是一个双向队列,可以从左右两边插入或删除

>>> import collections
>>> d = collections.deque()
>>> d.append(1)
>>> d.append(2)
>>> d.append(3)
>>> d.appendleft(1)
>>> print(d)
>>> d.extend([3,4,5])
>>> d.extendleft([3,4,5])
>>> print(d)
>>> d.pop()
>>> d.popleft()
>>> print(d)
deque([1, 1, 2, 3])
deque([5, 4, 3, 1, 1, 2, 3, 3, 4, 5])
deque([4, 3, 1, 1, 2, 3, 3, 4])

让字典保持有序

python2.7的话 字典是无序的 如何让字典保持有序 需要使用collections.OrderedDict

python3已经有序了,直接使用dict就可以了

>>> d = {}
>>> d['Jim'] = (1, 35)
>>> d['Leo'] = (2, 40)
>>> d['Bob'] = (3, 45)
>>> 
# py2
>>> for k in d:
         print (k)
Bob
Jim
Leo

# py3
>>> for k in d:
         print (k)
Jim
Leo
Bob

br/>

猜你喜欢

转载自www.cnblogs.com/wangjiale1024/p/10311746.html