#17 random&json模块
本节将讲解两个模块,一个是随机模块random,一个是字符串和字典之间的转换模块json,这两个模块使用率还是很高的,来认识一下!
一、random模块
random的官方文档:https://docs.python.org/3.5/library/random.html
这里只记录常用的方法:
1 2 3 4 5 6 7
| In [3]: import random
In [4]: random.random() Out[4]: 0.8952565343053827
In [5]: random.random() Out[5]: 0.6822327896680234
|
1 2 3 4 5 6 7
| In [12]: import random
In [13]: random.randint(1,10) Out[13]: 5
In [14]: random.randint(1,10) Out[14]: 2
|
1 2 3 4 5 6 7
| In [15]: import random
In [17]: random.uniform(1.1,9.9) Out[17]: 8.136851906531758
In [18]: random.uniform(1.1,9.9) Out[18]: 8.24769737404256
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| In [19]: import random
In [20]: random.choice('I am MinuteSheep') Out[20]: 'u'
In [22]: random.choice('I am MinuteSheep') Out[22]: 'I'
In [25]: random.choice('I am MinuteSheep') Out[25]: ' '
In [26]: random.choice([1,2,4,6,9]) Out[26]: 2
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| In [28]: import random
In [29]: random.randrange(1,15) Out[29]: 12
In [32]: random.randrange(1,15,2) Out[32]: 11
In [33]: random.randrange(1,15,2) Out[33]: 3
In [34]: random.randrange(1,15,2) Out[34]: 9
In [35]: random.randrange(1,15,2) Out[35]: 1
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| In [39]: import random
In [40]: num = [1,2,3,4,5,6,7]
In [41]: random.shuffle(num)
In [42]: num Out[42]: [3, 7, 5, 1, 2, 6, 4]
In [43]: random.shuffle(num)
In [44]: num Out[44]: [1, 6, 4, 3, 5, 2, 7]
|
二、json模块
json官方文档:https://docs.python.org/3.5/library/json.html
大家可能知道一些常见的文件格式,比如:txt、pdf、exe、word、ppt、excel、zip等等,在程序员这里,通常数据保存为json格式,尤其是作前端的程序员,json实质上是类似字典的字符串,比如:
1
| '{"name":"MinuteSheep", "age":100, "gender": "male"}'
|
乍一看,是个字典;再一看,是个字符串!
如果想要提取出这段字符串的‘name’信息,想要对其进行字典的操作显然是不可能的,这时候就要用到json模块了:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| In [60]: import json In [61]: info = '{"name":"MinuteSheep", "age":100, "gender": "male"}'
In [62]: type(info) Out[62]: str
In [63]: info_dict = json.loads(info)
In [64]: info_dict Out[64]: {'age': 100, 'gender': 'male', 'name': 'MinuteSheep'}
In [65]: info_dict['name'] Out[65]: 'MinuteSheep'
|
同样,对于字典,也可以将其转换为字符串形式:
1 2 3 4 5 6 7 8 9 10 11 12
| In [68]: import json
In [69]: info = {'age': 100, 'gender': 'male', 'name': 'MinuteSheep'}
In [70]: type(info) Out[70]: dict
In [71]: json.dumps(info) Out[71]: '{"age": 100, "gender": "male", "name": "MinuteSheep"}'
|
json最常用的方法就是这两个,还有两个用的不多的方法:json.load(),json.dump(),这两个用于写入文件,具体使用请查看官方文档