python 2-7 如何实现用户的历史记录功能(最多n条)collections.deque/pickle持久存储
来源:互联网 发布:淘宝联盟优惠券链接 编辑:程序博客网 时间:2024/06/15 16:27
2-7 如何实现用户的历史记录功能(最多n条)collections.deque/pickle持久存储
使用collections deque,设定最大元素个数N,如果超过N,就会把最早进入队列的元素给挤掉
可以用pickle 对队列对象实现持久化存储,再次运行时候可以重新load
deque和pickle的用法
deque1 = deque([],5)deque1.append(k)f = open("save.data",'w')pickle.dump(deque1, f)deque1 = pickle.load(open("save.data"))
一个真实的例子
比如一个例子就是竞猜答案,我们可以把用户最近5次的猜的数字保留下来,多于5次的,就会把最早一次的挤出队列
同样程序如果重新启动时候也还要把历史数据给重新load进来,程序重新启动时候读到历史数据
from collections import dequeimport picklefrom random import randintimport osresult = randint(1,100)print "result is ",resultdeque1 = deque([],5)if os.path.isfile("save.data"): deque1 = pickle.load(open("save.data")) while True: k = raw_input("\nplease input your guess number: ") if k.isdigit(): k = int(k) elif k == 'h' or k == 'H': print "your input history is ",list(deque1) else: continue if k != result: if k > result: print "your number is greater than result\n" else: print "your number is less than result\n" deque1.append(k) else: print "It was good result..." deque1.append(k) breakf = open("save.data",'w')pickle.dump(deque1, f)
deque的帮助信息
>>> help(collections.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 | | 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
pickle的帮助信息
>>> help(pickle)Help on module pickle:NAME pickle - Create portable serialized representations of Python objects.FILE /opt/swe/tools/ext/gnu/python-2.7.3/lib/python2.7/pickle.pyDESCRIPTION See module cPickle for a (much) faster implementation. See module copy_reg for a mechanism for registering custom picklers. See module pickletools source for extensive comments. Classes: Pickler Unpickler Functions: dump(object, file) dumps(object) -> string load(file) -> object loads(string) -> object Misc variables: __version__ format_version compatible_formatsCLASSES exceptions.Exception(exceptions.BaseException) PickleError PicklingError UnpicklingError Pickler Unpickler Functions: dump(object, file) dumps(object) -> string load(file) -> object loads(string) -> object Misc variables: __version__ format_version compatible_formatsCLASSES exceptions.Exception(exceptions.BaseException) PickleError PicklingError UnpicklingError Pickler Unpickler class PickleError(exceptions.Exception) | A common base class for the other pickling exceptions. | | Method resolution order: | PickleError | exceptions.Exception | exceptions.BaseException | __builtin__.object | | Data descriptors defined here: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Methods inherited from exceptions.Exception: | | __init__(...) | x.__init__(...) initializes x; see help(type(x)) for signature | | ---------------------------------------------------------------------- | Data and other attributes inherited from exceptions.Exception: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | ---------------------------------------------------------------------- | Methods inherited from exceptions.BaseException: | | __delattr__(...) | x.__delattr__('name') <==> del x.name | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __reduce__(...) | | __repr__(...) | x.__repr__() <==> repr(x) | | __setattr__(...) | x.__setattr__('name', value) <==> x.name = value | | __setstate__(...) | | __str__(...) | x.__str__() <==> str(x) | | __unicode__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.BaseException: | | __dict__ | | args | | message class Pickler | Methods defined here: | | __init__(self, file, protocol=None) | This takes a file-like object for writing a pickle data stream. | | The optional protocol argument tells the pickler to use the | given protocol; supported protocols are 0, 1, 2. The default | protocol is 0, to be backwards compatible. (Protocol 0 is the | only protocol that can be written to a file opened in text | mode and read back successfully. When using a protocol higher | than 0, make sure the file is opened in binary mode, both when | pickling and unpickling.) | | Protocol 1 is more efficient than protocol 0; protocol 2 is | more efficient than protocol 1. | | Specifying a negative protocol version selects the highest | protocol version supported. The higher the protocol used, the | more recent the version of Python needed to read the pickle | produced. | | The file parameter must have a write() method that accepts a single | string argument. It can thus be an open file object, a StringIO | object, or any other custom object that meets this interface. | | clear_memo(self) | Clears the pickler's "memo". | | The memo is the data structure that remembers which objects the | pickler has already seen, so that shared or recursive objects are | pickled by reference and not by value. This method is useful when | re-using picklers. | | dump(self, obj) | Write a pickled representation of obj to the open file. | | get(self, i, pack=<built-in function pack>) | # Return a GET (BINGET, LONG_BINGET) opcode string, with argument i. | | memoize(self, obj) | Store an object in the memo. | | persistent_id(self, obj) | | put(self, i, pack=<built-in function pack>) | # Return a PUT (BINPUT, LONG_BINPUT) opcode string, with argument i. | | save(self, obj) | | save_bool(self, obj) | | save_dict(self, obj) | | save_empty_tuple(self, obj) | # save_empty_tuple() isn't used by anything in Python 2.3. However, I | # found a Pickler subclass in Zope3 that calls it, so it's not harmless | # to remove it. | | save_float(self, obj, pack=<built-in function pack>) | | save_global(self, obj, name=None, pack=<built-in function pack>) | | save_inst(self, obj) | | save_int(self, obj, pack=<built-in function pack>) | | save_list(self, obj) | | save_long(self, obj, pack=<built-in function pack>) | | save_none(self, obj) | | save_pers(self, pid) | | save_reduce(self, func, args, state=None, listitems=None, dictitems=None, obj=None) | | save_string(self, obj, pack=<built-in function pack>) | | save_tuple(self, obj) | | save_unicode(self, obj, pack=<built-in function pack>) | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | dispatch = {<type 'classobj'>: <function save_global>, <type 'instance... class PicklingError(PickleError) | This exception is raised when an unpicklable object is passed to the | dump() method. | | Method resolution order: | PicklingError | PickleError | exceptions.Exception | exceptions.BaseException | __builtin__.object | | Data descriptors inherited from PickleError: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Methods inherited from exceptions.Exception: | | __init__(...) | x.__init__(...) initializes x; see help(type(x)) for signature | | ---------------------------------------------------------------------- | Data and other attributes inherited from exceptions.Exception: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | ---------------------------------------------------------------------- | Methods inherited from exceptions.BaseException: | | __delattr__(...) | x.__delattr__('name') <==> del x.name | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __reduce__(...) | | __repr__(...) | x.__repr__() <==> repr(x) | | __setattr__(...) | x.__setattr__('name', value) <==> x.name = value | | __setstate__(...) | | __str__(...) | x.__str__() <==> str(x) | | __unicode__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.BaseException: | | __dict__ | | args | | message class Unpickler | Methods defined here: | | __init__(self, file) | This takes a file-like object for reading a pickle data stream. | | The protocol version of the pickle is detected automatically, so no | proto argument is needed. | | The file-like object must have two methods, a read() method that | takes an integer argument, and a readline() method that requires no | arguments. Both methods should return a string. Thus file-like | object can be a file object opened for reading, a StringIO object, | or any other custom object that meets this interface. | | find_class(self, module, name) | | get_extension(self, code) | | load(self) | Read a pickled object representation from the open file. | | Return the reconstituted object hierarchy specified in the file. | | load_append(self) | | load_appends(self) | | load_binfloat(self, unpack=<built-in function unpack>) | | load_binget(self) | | load_binint(self) | | load_binint1(self) | | load_binint2(self) | | load_binpersid(self) | | load_binput(self) | | load_binstring(self) | | load_binunicode(self) | | load_build(self) | | load_dict(self) | | load_dup(self) | | load_empty_dictionary(self) | | load_empty_list(self) | | load_empty_tuple(self) | | load_eof(self) | | load_ext1(self) | | load_ext2(self) | | load_ext4(self) | | load_false(self) | | load_float(self) | | load_get(self) | | load_global(self) | | load_inst(self) | | load_int(self) | | load_list(self) | | load_long(self) | | load_long1(self) | | load_long4(self) | | load_long_binget(self) | | load_long_binput(self) | | load_mark(self) | | load_newobj(self) | | load_none(self) | | load_obj(self) | | load_persid(self) | | load_pop(self) | | load_pop_mark(self) | | load_proto(self) | | load_put(self) | | load_reduce(self) | | load_setitem(self) | | load_setitems(self) | | load_short_binstring(self) | | load_stop(self) | | load_string(self) | | load_true(self) | | load_tuple(self) | | load_tuple1(self) | | load_tuple2(self) | | load_tuple3(self) | | load_unicode(self) | | marker(self) | # Return largest index k such that self.stack[k] is self.mark. | # If the stack doesn't contain a mark, eventually raises IndexError. | # This could be sped by maintaining another stack, of indices at which | # the mark appears. For that matter, the latter stack would suffice, | # and we wouldn't need to push mark objects on self.stack at all. | # Doing so is probably a good thing, though, since if the pickle is | # corrupt (or hostile) we may get a clue from finding self.mark embedded | # in unpickled objects. | | ---------------------------------------------------------------------- | Data and other attributes defined here: | | dispatch = {'': <function load_eof>, '(': <function load_mark>, ')': <... class UnpicklingError(PickleError) | This exception is raised when there is a problem unpickling an object, | such as a security violation. | | Note that other exceptions may also be raised during unpickling, including | (but not necessarily limited to) AttributeError, EOFError, ImportError, | and IndexError. | | Method resolution order: | UnpicklingError | PickleError | exceptions.Exception | exceptions.BaseException | __builtin__.object | | Data descriptors inherited from PickleError: | | __weakref__ | list of weak references to the object (if defined) | | ---------------------------------------------------------------------- | Methods inherited from exceptions.Exception: | | __init__(...) | x.__init__(...) initializes x; see help(type(x)) for signature | | ---------------------------------------------------------------------- | Data and other attributes inherited from exceptions.Exception: | | __new__ = <built-in method __new__ of type object> | T.__new__(S, ...) -> a new object with type S, a subtype of T | | ---------------------------------------------------------------------- | Methods inherited from exceptions.BaseException: | | __delattr__(...) | x.__delattr__('name') <==> del x.name | | __getattribute__(...) | x.__getattribute__('name') <==> x.name | | __getitem__(...) | x.__getitem__(y) <==> x[y] | | __getslice__(...) | x.__getslice__(i, j) <==> x[i:j] | | Use of negative indices is not supported. | | __reduce__(...) | | __repr__(...) | x.__repr__() <==> repr(x) | | __setattr__(...) | x.__setattr__('name', value) <==> x.name = value | | __setstate__(...) | | __str__(...) | x.__str__() <==> str(x) | | __unicode__(...) | | ---------------------------------------------------------------------- | Data descriptors inherited from exceptions.BaseException: | | __dict__ | | args | | messageFUNCTIONS dump(obj, file, protocol=None) dumps(obj, protocol=None) load(file) loads(str)DATA APPEND = 'a' APPENDS = 'e' BINFLOAT = 'G' BINGET = 'h' BININT = 'J' BININT1 = 'K' BININT2 = 'M' BINPERSID = 'Q' BINPUT = 'q' BINSTRING = 'T' BINUNICODE = 'X' BUILD = 'b' DICT = 'd' DUP = '2' EMPTY_DICT = '}' EMPTY_LIST = ']' EMPTY_TUPLE = ')' EXT1 = '\x82' EXT2 = '\x83' EXT4 = '\x84' FALSE = 'I00\n' FLOAT = 'F' GET = 'g' GLOBAL = 'c' HIGHEST_PROTOCOL = 2 INST = 'i' INT = 'I' LIST = 'l' LONG = 'L' LONG1 = '\x8a' LONG4 = '\x8b' LONG_BINGET = 'j' LONG_BINPUT = 'r' MARK = '(' NEWFALSE = '\x89' NEWOBJ = '\x81' NEWTRUE = '\x88' NONE = 'N' OBJ = 'o' PERSID = 'P' POP = '0' POP_MARK = '1' PROTO = '\x80' PUT = 'p' REDUCE = 'R' SETITEM = 's' SETITEMS = 'u' SHORT_BINSTRING = 'U' STOP = '.' STRING = 'S' TRUE = 'I01\n' TUPLE = 't' TUPLE1 = '\x85' TUPLE2 = '\x86' TUPLE3 = '\x87' UNICODE = 'V' __all__ = ['PickleError', 'PicklingError', 'UnpicklingError', 'Pickler... __version__ = '$Revision: 72223 $'VERSION 72223
0 0
- python 2-7 如何实现用户的历史记录功能(最多n条)collections.deque/pickle持久存储
- 如何实现用户的历史记录功能(最多n条)
- python-5-如何实现用户的历史记录功能(最多n条)?
- Python高级编程-如何实现用户的历史记录功能?
- 2-7实现用户的历史记录功能
- python实现字典树的插入、查找功能并基于pickle模块持久化存储字典树
- python高效编程技巧6(如何实现用户的历史记录功能)
- python数据持久存储:pickle模块的基本使用
- python数据持久存储:pickle模块的基本使用
- python数据持久存储:pickle模块的基本使用
- python数据持久存储:pickle模块的基本使用
- python数据持久存储:pickle模块的基本使用
- python数据持久存储:pickle模块的基本使用
- python数据持久存储:pickle模块的基本使用
- python数据持久存储:pickle模块的基本使用
- python数据持久存储:pickle模块的基本使用
- python数据持久存储:pickle模块的基本使用
- python数据持久存储:pickle模块的基本使用
- 程序员面试金典——解题总结: 9.15 数据库 15.1编写SQL查询,列出租住不止一套公寓的承租人。
- 用例图
- 接口类和抽象类的区别
- Spring Boot配置方式
- 【bzoj3944】Sum
- python 2-7 如何实现用户的历史记录功能(最多n条)collections.deque/pickle持久存储
- ViewPager + Fragment处理两个Fragment的点击跳转以及之间的传递数据
- 顺序表应用7:最大子段和之分治递归法
- PHP命名空间(Namespace)的使用详解
- 安全态势感知:一些哲学思考
- ORM原型概念
- 踹图_AC自动机
- DotNet加密方式解析--对称加密
- Python-读写文件