当前位置: 首页 > 图灵资讯 > 行业资讯> python list怎样生成随机数

python list怎样生成随机数

发布时间:2025-05-09 10:54:31

第一,最直接的方法:用numpy.生成随机数组的random模块

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

importnumpyasnp
>>>np.random.rand(10)
array(0.138505521、0.57468244、0.370697、0.31823162、0.58358377、0.97177937、0.76468244、0.37、0.31823377、0.7777937、0.7640592、0.11269547

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

>>>np.random.randn(10)
array([-0.42625455,-1.86248727,0.96332,-0.32809754,-0.79697695,-0.07145189,2.89728643,2.32095237,
-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)

相关推荐:Python入门教程

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
[1752943608]
>>>>np.random.permutation(10)
array(1、7、4、3、0、9、2、5、8、6)

二、用random模块构建自己

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

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

>>>importrandom
>>>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作为步长列表中的随机整数。同样,如果start大于stop,则三个参数为整数(或小数位为0) ,setp必须是负数.step不能是0.

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

5、生成随机数组

使用random.randint方法可以构建列表:

importrandom
defrandom_list(start,stop,length):
iflength>=0:
length=int(length)
start,stop=(int(start),int(stop))ifstart<=stopelse(int(stop),int(start))
random_list=[]
foriinrange(length):
random_list.append(random.randint(start,stop))
returnrandom_list

相关文章

python3兼容python2吗

python3兼容python2吗

2025-05-09
python3 whl怎么安装

python3 whl怎么安装

2025-05-09
python 字典怎么提取value

python 字典怎么提取value

2025-05-09
python 怎样计算字符串的长度

python 怎样计算字符串的长度

2025-05-09
python 怎么样反向输出字符串

python 怎么样反向输出字符串

2025-05-09
python 怎么判断字符串开头

python 怎么判断字符串开头

2025-05-09