首页 Python随机数小结
文章
取消

Python随机数小结

本文以 Python3.5 为例。

  1. 0-1之间的一个浮点数
1
2
3
>>> import random
>>> random.random()
0.6959072143294135

也可使用 numpy 生成

1
2
3
>>> import numpy as np
>>> np.random.random()
0.42391828187048664
  1. a-b之间的一个浮点数
1
2
3
>>> import random
>>> random.uniform(1,1000)
488.24204092358707
  1. a-b之间的一个整数
1
2
3
>>> import random
>>> random.randint(1,1000)
880

或者

1
2
3
>>> import numpy as np
>>> np.random.randint(10,23)
17

生成n个:

1
2
3
>>> np.random.randint(10,23,34)
array([20, 10, 12, 16, 14, 11, 22, 18, 15, 21, 20, 19, 16, 16, 14, 14, 10,
       20, 14, 20, 10, 16, 13, 20, 21, 10, 10, 11, 12, 19, 12, 11, 10, 13])
  1. n 比特长度的随机数,即0到2的n次方区间
1
2
3
>>> import random
>>> random.getrandbits(5)
9
  1. a-b之间的步长为c的一个整数
1
2
3
>>> import random
>>> random.randrange(1,1000,3)
7

3为步长,7=1+3*2 步长选填,不填时默认为1

  1. n字节的随机二进制字符串,常用于加密使用
1
2
3
>>> import os
>>> os.urandom(4)
b'\xe5\x12\\\x1a'
  1. 数组中的随机元素
1
2
3
4
>>> import random
>>> l=['a',3,8,'abc',4.9]
>>> random.choice(l)
'abc'
  1. 数组中的若干随机元素
1
2
3
4
>>> import random
>>> l=['a',3,8,'abc',4.9]
>>> random.sample(l,3)
[4.9, 'abc', 'a']
  1. 打乱数组元素顺序
1
2
3
4
5
>>> import random
>>> l=[10,58,8,-1,45,2,9]
>>> random.shuffle(l)
>>> l
[8, 2, 10, -1, 45, 9, 58]
本文由作者按照 CC BY 4.0 进行授权