JSON, pickle, random, Hashlib, collections for Python's common modules

Source: Internet
Author: User
Tags sha1

1. JSON and Pickle

JSON is used to convert between string and Python data types
Pickle is used to convert between Python-specific types and Python data types
There are four methods available for both JSON and Pickle dumps,dump,loads,load

 ##json Dumps ()##转换成字符串Loads ()##将json编码的字符串再转换为python的数据结构Dump ()##转换成字符串并存存储到文件中Load ()##从数据文件中读取数据 and convert the JSON-encoded string into a Python data structure>>>Print(Json.dumps (['AA','BB','cc']))["AA","BB","cc"]>>>Print(Json.loads ('["AA", "BB", "CC"]'))['AA','BB','cc'] ##pickle Dumps ()##将数据通过特殊的形式转换为只有python语言认识的字符串Loads ()##将pickle数据转换为python的数据结构Dump ()##将数据通过特殊的形式转换为只有python语言认识的字符串, and write the fileLoad ()##从数据文件中读取数据, and convert to Python 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 ()#a random decimal between #0Random.uniform (1,3)#random decimal between #1 toRandom.randint (1,5)#a random integer between #[1,5]Random.randrange (1,10,2)##[1,10) random odd number, interval of 2Random.choice ([1,' at', [4,5]])##随机选择一个返回Random.sample ([1,' at', [4,5]],2]##随机选择多个返回, the number returned is the second argument of the functionRandom.shuffle ([1,3,5,7,9])##打乱列表顺序# #返回验证码ImportRandomdefv_code (): Code="'     forIinchRange (5): Num=random.randint (0,9) Alf=CHR (Random.randint (65,90)) Add=Random.choice ([num,alf]) code="". Join ([Code,str (add)])returnCodePrint(V_code ())

3, Hashlib

Hashlib provides a common digest algorithm, such as MD5,SHA1 and so on.

##md5计算MD5 = HASHLIB.MD5 ("Key". Encode ("UTF8"))##可以添加秘钥, the secret key can be a user ID, so even if the password is the same, the MD5 after the encryption is not the sameMd5.update (b'Love Fly')Print(Md5.hexdigest ())##SHA1SHA1 = HASHLIB.SHA1 ("Key". Encode ("UTF8")) Sha1.update (b'Love Fly')Print(Sha1.hexdigest ())##计算MD5>>>ImportHashlib>>> MD5 =hashlib.md5 ()>>> Md5.update (b'Love Fly')>>>Print(Md5.hexdigest ()) 61976ec704dbce25ccb37ecacef1e4d6##如果数据量很大, you can call Update () multiple times in chunks, and the result is the same as the final calculation>>>ImportHashlib>>> 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 that provides a number of useful collection classes and is a complement to the default data structure of Python

##namedtuple是一个函数, it is used to create a custom tuple object, and it specifies the number of tuple elements, and you can refer to an element of a tuple using a property rather than an index. >>> fromCollectionsImportNamedtuple>>> 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 Ordereddict and so on. 1. Namedtuple: Generates a tuple that can use a name to access the content of an element2. Deque: Double-ended queue that can quickly append and eject objects from the other side3. Counter: Counter, mainly used to count4. Ordereddict: Ordered dictionary5. Defaultdict: Dictionary with default values##deque: The list inserts and deletes elements are slow and the data volume is large, and insertions and deletions are inefficient. Deque is a two-way list for efficient insert and delete operations, suitable for queues and stacks. >>> fromCollectionsImportdeque>>> q = deque (['a','b','C'])>>> Q.append ('D')##默认添加列表最后一项>>> Q.appendleft ('e')##添加到列表第一项>>>Qdeque (['e','a','b','C','D'])>>> Q.pop ()##默认删除列表最后一个元素'D'>>> Q.popleft ()##删除列表的第一个元素'e'>>>Qdeque (['a','b','C'])##defaultdict使用字典时, if the referenced key does not exist, it throws Keyerror, and if you want the key to be absent, return a default value, you can use Defaultdict.X=defaultdict (Lambda:'N /A')##OrderedDict有序字典的应用. The order of the ordereddict is in the order in which they are inserted, not in the key. ##Counter简单的计数器, for example, the number of occurrences of a statistical character. 

JSON, pickle, random, Hashlib, collections for Python's common modules

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.