2-7实现用户的历史记录功能
1、实现方法
方法一:使用标准库collections中的deque
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
from random import randint from collections import deque N = randint(0,100) histroy = deque([],5) #建立一个空列表队列,队列容量为5 def guess(k): if k==N: print("right") return True; elif 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 num:") if line.isdigit(): #判断是否是数字 k = int(line) histroy.append(k) #队列里添加 if guess(k): break; elif line == "histroy" or line == "h?" or lint == "H?": print(list(histroy)) #将队列转为列表打印输出
测试实现的结果:
please input a num:15
15 is less than N
please input a num:50
50 is greater than N
please input a num:30
30 is greater than N
please input a num:20
20 is less than N
please input a num:25
25 is greater than N
please input a num:24
24 is greater than N
please input a num:23
23 is greater than N
please input a num:histroy
[30, 20, 25, 24, 23]
please input a num:18
18 is less than N
please input a num:histroy
[20, 25, 24, 23, 18]
please input a num:22
22 is greater than N
please input a num:21
right
>>>
方法二:pickle将对象保存到文件和从文件中读取
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
>>> from collections import deque >>> dq = deque([1,3,2,4,5],5) >>> dq deque([1, 3, 2, 4, 5], maxlen=5) >>> import pickle >>> pickle.dump(dq,open('histroy.txt','w')) >>> q2 = pickle.load(open('histroy.txt')) >>> q2 deque([1, 3, 2, 4, 5], maxlen=5)
测试的结果为:
2、扩展知识:
2.1 deque
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
>>> help(deque) Help on class deque in module collections: class deque(__builtin__.object) | deque([iterable[, maxlen]]) --> deque object | | Build an ordered collection with optimized access from its endpoints. | | Methods defined here: | | __copy__(...) | Return a shallow copy of a deque. | | __delitem__(...) | x.__delitem__(y) <==> del x[y] | | __eq__(...) | x.__eq__(y) <==> x==y | | __ge__(...) | x.__ge__(y) <==> x>=y | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __gt__(...) | x.__gt__(y) <==> x>y | | __iadd__(...) | x.__iadd__(y) <==> x+=y | | __init__(...) | x.__init__(...) initializes x; see help(type(x)) for signature | | __iter__(...) | x.__iter__() <==> iter(x) | | __le__(...) | x.__le__(y) <==> x<=y | | __len__(...) | x.__len__() <==> len(x) | | __lt__(...) | x.__lt__(y) <==> x<y | | __ne__(...) | x.__ne__(y) <==> x!=y | | __reduce__(...) | Return state information for pickling. | | __repr__(...) | x.__repr__() <==> repr(x) | | __reversed__(...) | D.__reversed__() -- return a reverse iterator over the deque | | __setitem__(...) | x.__setitem__(i, y) <==> x[i]=y | | __sizeof__(...) | D.__sizeof__() -- size of D in memory, in bytes | | append(...) | Add an element to the right side of the deque. | | appendleft(...) | Add an element to the left side of the deque. | | clear(...) | Remove all elements from the deque. | | count(...) | D.count(value) -> integer -- return number of occurrences of value | | extend(...) | Extend the right side of the deque with elements from the iterable | | extendleft(...) | Extend the left side of the deque with elements from the iterable | | pop(...) | Remove and return the rightmost element. | | popleft(...) | Remove and return the leftmost element. | | remove(...) | D.remove(value) -- remove first occurrence of value. | | reverse(...) | D.reverse() -- reverse *IN PLACE* | | rotate(...) | Rotate the deque n steps to the right (default n=1). If n is negative, rotates left. | | ---------------------------------------------------------------------- | Data descriptors defined here: | | maxlen | maximum size of a deque or None if unbounded | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | __hash__ = None | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T
>>> from collections import deque >>> >>> dq = deque([],5) >>> dq deque([], maxlen=5) >>> dq.append(1) >>> dq deque([1], maxlen=5) >>> dq.append(2) >>> dq deque([1, 2], maxlen=5) >>> dq[1] 2 >>> dq.append(3) >>> dq.append(4) >>> dq.append(5) >>> dq deque([1, 2, 3, 4, 5], maxlen=5) >>> dq[0] 1 >>> dq.append(6) >>> dq deque([2, 3, 4, 5, 6], maxlen=5) >>> dq[0] 2
使用list存储数据时,按索引访问元素很快,但是插入和删除元素就很慢了,因为list是线性存储,数据量大的时候,插入和删除效率很低。
deque是为了高效实现插入和删除操作的双向列表,适合用于队列和栈:
>>> q = deque(['a','b','c']) >>> q.append('d') >>> q.appendleft('y') >>> q deque(['y', 'a', 'b', 'c', 'd'])
deque除了实现list的append()和pop()外,还支持appendleft()和popleft(),这样就可以非常高效地往头部添加或删除元素。
2.2 isdigit()
>>> help(str.isdigit) Help on method_descriptor: isdigit(...) S.isdigit() -> bool Return True if all characters in S are digits and there is at least one character in S, False otherwise.
只有对象为数字时,返回True
2.3 pickle
把变量从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling。序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。Python提供了pickle模块来实现序列化。
2.3.1 pickle.dumps()
>>> help(pickle.dumps) Help on function dumps in module pickle: dumps(obj, protocol=None)
pickle.dumps()方法把任意对象序列化成一个bytes,然后,就可以把这个bytes写入文件。
>>> d = dict(name = 'Bob',age=20,score =88) >>> pickle.dumps(d)
Py2输出:
"(dp0\nS'age'\np1\nI20\nsS'score'\np2\nI88\nsS'name'\np3\nS'Bob'\np4\ns."
Py3输出
b'\x80\x03}q\x00(X\x03\x00\x00\x00ageq\x01K\x14X\x05\x00\x00\x00scoreq\x02KXX\x04\x00\x00\x00nameq\x03X\x03\x00\x00\x00Bobq\x04u.'
2.3.2 pickle.dump()和pickle.load()
如上面本例中
另一个方法pickle.dump()直接把对象序列化后写入一个file-like Object:
看看写入的dump.txt文件,一堆乱七八糟的内容,这些都是Python保存的对象内部信息。
当我们要把对象从磁盘读到内存时,可以先把内容读到一个bytes,然后用pickle.loads()方法反序列化出对象,也可以直接用pickle.load()方法从一个file-like Object中直接反序列化出对象。我们打开另一个Python命令行来反序列化刚才保存的对象:
变量的内容又回来了!
当然,这个变量和原来的变量是完全不相干的对象,它们只是内容相同而已。
注意:Pickle的问题和所有其他编程语言特有的序列化问题一样,就是它只能用于Python,并且可能不同版本的Python彼此都不兼容,因此,只能用Pickle保存那些不重要的数据,不能成功地反序列化也没关系。
posted on 2018-04-12 09:22 石中玉smulngy 阅读(153) 评论(0) 编辑 收藏 举报