Python Intensive Training Note (7)-use the deque queue and save the object as a file,
The deque object in the collections module is a queue with the first-in-first-out principle for normal queues. We can use this object to save data.
For example, the system starts to randomly roll a game with a guess number ~ Then, the keyboard starts to receive your input. The number system will tell you whether the input is larger or smaller than the random number until you have guessed it. For example:
For the code, see:
from collections import dequefrom random import randintN = randint(0, 100)history = deque([], 5)def guess(k): if k == N: print "right" return True if k < N: print "%s is less-than N" % k if k > N: print "%s is greater-than N" % k return Falsewhile True: line = raw_input("please input a number:") if line.isdigit(): k = int(line) history.append(k) if guess(k): break elif line == "history" or line == "h?": print list(history)
Here we use this deque object, which records the previous input history, so that we can remember it to avoid repeated guesses.
Deque ([], 5)
Deque accepts two parameters. The first parameter is the initial value of the queue and the second parameter specifies the bucket. The length is 5. If the length exceeds 5, the first number goes out and the latest number enters.
>>> d = deque([], 5)>>> d.append(1)>>> d.append(2)>>> d.append(3)>>> d.append(4)>>> d.append(5)>>> ddeque([1, 2, 3, 4, 5], maxlen=5)>>> d.append(6)>>> ddeque([2, 3, 4, 5, 6], maxlen=5)
Save object
For the above queue d, we hope to save it and it can be used again next time the program restarts. We can use the pickle module.
Save
>>> Import pickle
>>> S = [1, 2, 3, 4, 5] >>> pickle. dump (s, open ('object', 'w') >>> # in this way, the s object is stored in the object file, and the file has a write permission.
Import
>>> import pickle>>> s = pickle.load('object')>>> s[1, 2, 3, 4, 5]