1. json and pickle
json is used for conversion between strings and Python data types
pickle is used for conversion between python-specific types and python-specific data types
json and pickle provide four methods: dumps,dump,loads,load
##json dumps() ##Convert to a string loads() ##Converting json-coded strings to python data structures dump() ##Converting strings and storing them in files load() ##Read data from data files and convert json-encoded strings into python data structures >>> print(json.dumps(['aa', 'bb', 'cc'])) ["aa", "bb", "cc"] >>> print(json.loads('["aa", "bb", "cc"]')) ['aa', 'bb', 'cc'] ##pickle dumps() ##Converting data in a special form to a string that only python knows loads() ##Converting pickle data to python data structure dump() ##Convert the data into a string that only python knows, and write it to a file load() ##Read data from a data file and convert it to python's data structure >>> print(pickle.dumps(['aa', 'bb', 'cc'])) b'\x80\x03]q\x00(X\x02\x00\x00\x00aaq\x01X\x02\x00\x00\x00bbq\x02X\x02\x00\x00\x00ccq\x03e.' >>> print(pickle.loads(b'\x80\x03]q\x00(X\x02\x00\x00\x00aaq\x01X\x02\x00\x00\x00bbq\x02X\x02\x00\x00\x00ccq\x03e.')) ['aa', 'bb', 'cc']
2,random
random.random() ##Random decimal between 0 and 1 random.uniform(1,3) ##Random decimal numbers between 1 and 3 random.randint(1,5) ##Random integers between [1,5] random.randrange(1,10,2) ##[1,10] Random odd numbers with intervals of 2 random.choice([1,'23',[4,5]]) ##Random selection of a return random.sample([1,'23',[4,5]],2) ##Random selection of multiple returns, the number of returns is the second parameter of the function random.shuffle([1,3,5,7,9]) ##Disturbing the order of lists ##Return validation code import random def v_code(): code = '' for i in range(5): num=random.randint(0,9) alf=chr(random.randint(65,90)) add=random.choice([num,alf]) code="".join([code,str(add)]) return code print(v_code())
3,hashlib
hashlib provides common summary algorithms, such as MD5, SHA1, and so on.
##md5 computing md5 = hashlib.md5("key".encode("utf8")) ##You can add a secret key, which can be a user id, so that even if the password is the same, the encrypted md5 will be different. md5.update(b'love fly') print(md5.hexdigest()) ##SHA1 sha1 = hashlib.sha1("key".encode("utf8")) sha1.update(b'love fly') print(sha1.hexdigest()) ##Calculate MD5 >>> import hashlib >>> md5 = hashlib.md5() >>> md5.update(b'love fly') >>> print(md5.hexdigest()) 61976ec704dbce25ccb37ecacef1e4d6 ##If the amount of data is large, update() can be called several times in blocks, and the final result is the same. >>> import hashlib >>> md5 = hashlib.md5() >>> md5.update(b'love') >>> md5.update(b' fly') >>> print(md5.hexdigest()) 61976ec704dbce25ccb37ecacef1e4d6
4,collections
ollections is a Python built-in collection module, which provides many useful collection classes and is a complement to python's default data structure.
## namedtuple is a function that creates a custom tuple object, specifies the number of tuple elements, and can refer to an element of a tuple with attributes rather than indexes. >>> from collections import namedtuple >>> colltuple = namedtuple('colltuple', ['x','y']) >>> col = colltuple('yong','fly') >>> col.x 'yong' >>> col.y 'fly' Based on the built-in data types (dict, list, set, tuple), the collections module also provides several additional data types: Counter, deque, defaultdict, namedtuple and Ordered Dict. 1.namedtuple: Generate tuple that can access element content by name 2.deque: Double-ended queue that can quickly append and push objects from the other side 3.Counter: Counter, mainly used for counting 4.OrderedDict: Ordered Dictionary 5.defaultdict: A dictionary with default values # # deque: list inserts and deletes elements very slowly, and when there is a large amount of data, insertion and deletion efficiency is very low. Deque is a bidirectional list for efficient insertion and deletion operations, suitable for queues and stacks. >>> from collections import deque >>> q = deque(['a','b','c']) > Q. append ('d') # # defaults to add the last item in the list > Q. appendleft ('e') # added to the first item in the list >>> q deque(['e', 'a', 'b', 'c', 'd']) > Q. pop ()# # Default Delete the Last Element of the List 'd' > Q. popleft ()# # Delete the first element of the list 'e' >>> q deque(['a', 'b', 'c']) When using a dictionary ## defaultdict, if the key referenced does not exist, a KeyError will be thrown. If you want the key to not exist, you can return a default value, you can use defaultdict. X=defaultdict(lambda: 'N/A') Application of OrderedDict Ordered Dictionary. OrderedDict is ordered in the order of insertion, not KEY. A simple counter # Counter, for example, counts the number of characters that appear.