random库包含两类函数,常用共8个
函数 | 描述 |
---|---|
seed(a=None) | 初始化给定的随机数种子,默认为当前系统时间 |
random | 生成一个[0.0, 1.0)之间的随机小数 |
示例:
import random
random.seed(10);
for i in range(10):
s = random.random();
print(s);
#运行结果
0.5714025946899135
0.4288890546751146
0.5780913011344704
0.20609823213950174
0.81332125135732
0.8235888725334455
0.6534725339011758
0.16022955651881965
0.5206693596399246
0.32777281162209315
import random
for i in range(10):
random.seed(10);
s = random.random();
print(s);
#运行结果
0.5714025946899135
0.5714025946899135
0.5714025946899135
0.5714025946899135
0.5714025946899135
0.5714025946899135
0.5714025946899135
0.5714025946899135
0.5714025946899135
0.5714025946899135
注意:每调用一次seed()函数,重新生成随机数序列,调用random()函数获得的随机数一样
函数 | 描述 |
---|---|
randint(a, b) | 生成一个[a, b]之间的整数 |
randrange(m,n[,k]) | 生成一个[m, n)之间以k为步长的随机函数 |
getrandbits(k) | 生成一个k比特长的随机整数 |
uniform(a, b) | 生成一个[a, b]之间的随机小数 |
choice(seq) | 从序列seq中随机选择一个元素 |
shuffle(seq) | 将序列seq中元素随机排列,返回打乱后的序列 |
示例:
import random
for i in range(10):
s = random.randint(10, 100);
print(s,end=",");
#运行结果
#58,27,80,15,58,50,20,72,71,59,
import random
for i in range(10):
s = random.randrange(10, 100, 5);
print(s,end=",");
#运行结果
#50,55,90,70,90,55,45,15,50,25,
import random
for i in range(10):
s = random.getrandbits(8);
print(s,end=",");
#运行结果
#101,27,188,129,110,180,230,135,136,192,
import random
for i in range(10):
s = random.uniform(10, 100);
print(s);
#运行结果
97.41249750228681
98.37395098206481
73.93762766960197
40.469986368734325
51.68469203969976
42.581909601354084
84.58121128394451
23.63826586377845
83.41580524463157
16.495669862038902
import random
a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
for i in range(10):
s = random.choice(a);
print(s, end=",");
#运行结果
#6,6,6,5,3,8,5,4,7,9,
import random
for i in range(10):
a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
random.shuffle(a);
print(a);
#运行结果
[2, 3, 5, 9, 8, 1, 6, 4, 7]
[7, 5, 2, 3, 1, 6, 9, 4, 8]
[8, 9, 6, 2, 5, 7, 3, 4, 1]
[9, 6, 8, 2, 4, 5, 3, 7, 1]
[5, 3, 2, 8, 4, 7, 9, 6, 1]
[4, 6, 3, 5, 9, 7, 2, 1, 8]
[8, 1, 3, 9, 5, 2, 6, 7, 4]
[8, 1, 5, 9, 3, 7, 4, 2, 6]
[1, 4, 6, 7, 3, 5, 8, 2, 9]
[1, 2, 9, 4, 6, 7, 5, 3, 8]
本文仅为学习Python记录,资料来源于中国大学MOOC《Python语言设计》—嵩天