python list怎样生成随机数

1,401次阅读
没有评论

python

一、最直接的方式:用numpy.random模块来生成随机数组

1、np.random.rand 用于生成[0.0, 1.0)之间的随机浮点数, 当没有参数时,返回一个随机浮点数,当有一个参数时,返回该参数长度大小的一维随机浮点数数组,参数建议是整数型,因为未来版本的numpy可能不支持非整形参数。

import numpy as np
>>> np.random.rand(10)
array([0.89103033,0.60550521,0.13856488,0.57468244,0.370697,0.31823162,0.58358377,0.97177935,0.76400592,0.11269547])

2、np.random.randn该函数返回一个样本,具有标准正态分布。

>>> np.random.randn(10)
array([-0.42625455,-1.86248727,0.96323332,-0.32809754,-0.79697695,-0.07145189,2.89728643,2.32095237,1.12925633,
-0.39210317])

3、np.random.randint(low[, high, size]) 返回随机的整数,位于半开区间 [low, high)。

>>> np.random.randint(10,size=10)
array([4, 1, 4, 3, 8, 2, 8, 5, 8, 9])

4、random_integers(low[, high, size]) 返回随机的整数,位于闭区间 [low, high]。

>>> np.random.random_integers(5)
2

5、 np.random.shuffle(x) 类似洗牌,打乱顺序;np.random.permutation(x)返回一个随机排列

>>> arr = np.arange(10)
>>> np.random.shuffle(arr)
>>> arr
[1 7 5 2 9 4 3 6 0 8]
>>>> np.random.permutation(10)
array([1, 7, 4, 3, 0, 9, 2, 5, 8, 6])

二、用random模块自己构造

1、random.randint(low, hight) -> 返回一个位于[low,hight]之间的整数

该函数接受两个参数,这两个参数必须是整数(或者小数位是0的浮点数),并且第一个参数必须不大于第二个参数

>>> import random
>>> random.randint(1,10)
6
>>> random.randint(1.0, 10.0)
1

2、random.random() -> 不接受参数,返回一个[0.0, 1.0)之间的浮点数

>>> random.random()
0.5885821552646049

3、random.uniform(val1, val2) -> 接受两个数字参数,返回两个数字区间的一个浮点数,不要求val1小于等于val2

>>> random.uniform(1,5.0)
4.485403087612088
>>> random.uniform(9.9, 2)
5.189511116007191

4、random.randrange(start, stop, step) -> 返回以start开始,stop结束,step为步长的列表中的随机整数,同样,三个参数均为整数(或者小数位为0),若start大于stop时 ,setp必须为负数.step不能是0.

>>> random.randrange(1, 100, 2)  #返回[1,100]之间的奇数
19
>>> random.ranrange(100, 1, -2)  #返回[100,1]之间的偶数
2

5、生成随机数组

使用random.randint方法构造一个列表即可:

import random
def random_list(start,stop,length):
    if length>=0:
        length=int(length)
  start, stop = (int(start), int(stop)) if start <= stop else (int(stop), int(start))
  random_list = []
    for i in range(length):
        random_list.append(random.randint(start, stop))
    return random_list
神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-06-23发表,共计1896字。
新手QQ群:570568346,欢迎进群讨论 Python51学习