jessieHJ 2020-05-31
random库包含两类函数,共八个
基本随机数函数:seed(),andom()
扩展随机数函数:randint(),getrandbits(),uniform(),randrange(),choice,shuffle()
一、基本随机数函数
1、seed(a=None)
初始化给定的随机数种子,默认(不调用seed()函数时)a为当前系统时间。只要种子相同,产生的随机序列也相同
import random as t r.seed(10) print(r.random()) r.seed(10) print(r.random())
运行结果:
0.5714025946899135 0.5714025946899135
2、random()
生成一个[0.0,1.0]之间的随机小数
import random as r print(r.random()) print(r.random())
运行结果:
0.5780913011344704 0.20609823213950174
二、扩展随机数函数是在基本随机数函数基础上拓展的随机数函数
import random as t print(r.randint(1,10)) print(r.randint(1,10)) print() print(r.randrange(10,100,10)) print(r.randrange(10,100,10)) print() print(r.getrandbits(10)) print(r.getrandbits(10)) print() print(r.uniform(4,9)) print(r.uniform(4,9)) print() a=[1,66,78,45,0,63,3,34,66,78] print(r.choice(a)) print(r.choice(a)) print() r.shuffle(a) print(a) r.shuffle(a) print(a)
运行结果:
8 9 40 50 611 373 4.579637349667651 7.913823016998503 1 45 [78, 45, 0, 1, 66, 63, 34, 66, 78, 3] [3, 66, 34, 45, 78, 1, 0, 66, 63, 78]