import random import numpy as np
In [2]: nd=np.arange(10) str=list('astrcdefghij') print("nd:",nd) print("str:",str)
Out[2]:
nd: [0 1 2 3 4 5 6 7 8 9]
str: ['a', 's', 't', 'r', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
In [3]:
#从已知序列中随机取一个元素 s=random.choice(str) print("s:",s)
Out[3]:
s: j
In 4]: #打乱从已知序列中元素顺序 random.shuffle(nd) print("nd:",nd) random.shuffle(str) print("str:",str)
Out[4]:
nd: [6 2 8 1 4 9 3 7 0 5]
str: ['r', 't', 'h', 's', 'i', 'g', 'j', 'c', 'e', 'f', 'a', 'd']
In [5]: #从已知序列中随机取固定数量的元素 nd=random.sample(list(nd),5) print("nd:",nd) str=random.sample(str,5) print("str:",str)
Out[5]:
nd: [7, 5, 2, 4, 3]
str: ['d', 's', 'a', 'e', 'c']
In [6]: #从已知序列中随机取5个元素合成一个字符串 str=''.join(random.sample(str,5)) print("str:",str)
Out[6]:
str: asedc
In [7]: #生成1个元素在(0,1)之间的随机浮点数 a=random.random() print("a:",a) a=np.random.rand() print("a:",a) nd=np.random.rand(3,4) print("nd:",nd)
Out[7]:
a: 0.8010321290923665
a: 0.5754016498568159
nd: [[0.11220787 0.05414973 0.13550454 0.56050772]
[0.56411102 0.71001862 0.91481863 0.41402596]
[0.39312503 0.64835602 0.43019934 0.59760637]]
In [8]: #生成1个元素在(0,1)之间的随机浮点数 a=random.uniform(1,10) print("a:",a) #生成1个元素在[0,10)之间的随机整数 a=random.randint(0,10) print("a:",a) #生成1个元素在[0,10)之间的2*4的随机矩阵 nd=np.random.randint(0,10,(2,4)) print("nd:",nd)
Out[8]:
a: 6.929493104692415
a: 5
nd: [[5 7 3 5]
[7 6 5 6]]
In [9]: #生成1个元素在[0,101)之间的偶数 random.randrange(0,101,2)
Out[9]:
96
要使每次生成的随机数固定则要在每次生成随机数之前设置随机数种子seed值,如:
In [10]: nd=np.arange(10) random.seed(0) random.shuffle(nd) print("nd:",nd) nd=np.arange(10) random.seed(0) random.shuffle(nd) print("nd:",nd)
Out[10]:
nd: [7 8 1 5 3 4 2 0 9 6]
nd: [7 8 1 5 3 4 2 0 9 6]
In [11] np.random.seed(0) nd=np.random.rand(5) print("nd:",nd) np.random.seed(0) nd=np.random.rand(5) print("nd:",nd)
Out[10]:
nd: [0.5488135 0.71518937 0.60276338 0.54488318 0.4236548 ]
nd: [0.5488135 0.71518937 0.60276338 0.54488318 0.4236548 ]