random用法

import random


1、获取0-1之间的随机数:

>>> random.random()
0.9158816305811902
  • 1
  • 2

2、获取[1,5]之间的随机

>>> random.randint(1,5)
5
  • 1
  • 2

3、取[2,5)之间的随机整数:

>>> random.randrange(2,5)    #这里可取值为2,3,4,不包含5(顾头不顾尾)
3
  • 1
  • 2

4、从传入的序列里面随机取值:

>>> random.choice("hello")     #这里的随机序列可以是字符串、列表、元组等
l
  • 1
  • 2

5、可指定从传入的序列里面随机取n位:

>>> random.sample("hello",2)   #随机取两位字符
['o', 'h']
  • 1
  • 2

6、获取指定区间内的随机浮点数:

>>> random.uniform(1,10)    #弥补random.random()只能取0-1的缺陷
2.9045665556565328
  • 1
  • 2

7、洗牌:

>>> i = [1,2,3,4,5,6]
>>> random.shuffle(i)
>>> print(i)     #这里打印i,列表内的元素已经打乱顺序。
[6, 5, 1, 3, 4, 2]
  • 1
  • 2
  • 3
  • 4

8、代码应用:随机获取字母数字组合的5位验证码

import random
verify = ''
for i in range(5):
    num2 = random.randint(0,5)
    if num2 == i:
        tmp = chr(random.randint(65,90))
    else:
        tmp = random.randint(0,9)
    verify += str(tmp)
print(verify)

 

 

 

0. np.random.RandomState

计算机实现的随机数生成通常为伪随机数生成器,为了使得具备随机性的代码最终的结果可复现,需要设置相同的种子值;

  • np.random.randn(…) ⇒ 
    • rng = np.random.RandomState(123)
    • rng.randn(…)

1. np.random.uniform()

首先从numpy.random.uniform说起(也即其他函数是对该函数的进一步封装)。

numpy.random.uniform(low=0.0, high=1.0, size=None)
  • 1
  • 1

顾名思义,从一个均匀分布([low, high):半开区间)中进行采样。

例如产生[1, 2)(五行五列):

>>> import numpy
>>> np.random.uniform(1, 2, (5, 5))
array([[ 1.16902081,  1.90805984,  1.30759311,  1.90598113,  1.32047656],
       [ 1.58571077,  1.88009484,  1.66531622,  1.0262826 ,  1.40534658],
       [ 1.81087389,  1.87981194,  1.65670468,  1.46972606,  1.66454007],
       [ 1.81041299,  1.52561204,  1.79701198,  1.17840313,  1.86364978],
       [ 1.72654371,  1.92870279,  1.11207754,  1.5091156 ,  1.35108628]])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

2. np.random.random is Alias for np.random.random_sample

alias: 别名;

>>> id(np.random.random) == id(np.random.random_sample)
True
  • 1
  • 2
  • 1
  • 2
numpy.random.random(size=None)
                # 已指定区间为[0., 1.),自然是float类型
  • 1
  • 2
  • 1
  • 2

必须以元组形式指定size

>>> np.random.random((2, 3))
array([[ 0.14367   ,  0.48649543,  0.38761876],
       [ 0.11565701,  0.6474381 ,  0.84394864]])
>>> np.random.random(2, 3)
TypeError: random_sample() takes at most 1 positional argument (2 given)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 1
  • 2
  • 3
  • 4
  • 5

3. np.random.rand: a convenience function for np.random.uniform(0, 1)

numpy.random.rand(d0, d1, ..., dn)
                # 以参数列表的形式指定参数,而非元组
                # 内部指定区间为[0., 1.)
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3
>>> np.random.rand(2, 2)
array([[ 0.9978749 ,  0.43597209],
       [ 0.30804578,  0.9632462 ]])

>>> np.random.rand((2, 2))
TypeError: an integer is required
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

4. 使用 np.random.RandomState() 获取随机数生成器

>> rng = np.random.RandomState(22)
>> rng.rand(2, 3)
array([[ 0.48168106,  0.42053804,  0.859182  ],
       [ 0.17116155,  0.33886396,  0.27053283]])

 

你可能感兴趣的:(python)