python随机生成数组的方法

发布时间:2020-07-01 16:42:13 作者:清晨
来源:亿速云 阅读:285

这篇文章主要介绍python随机生成数组的方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

python生成随机数组的方法:

1、使用random模块生成随机数组

python的random模块中有一些生成随机数字的方法,例如random.randint, random.random, random.uniform, random.randrange,这些函数大同小异,均是在返回指定范围内的一个整数或浮点数,下边简单解释一下这几个函数。

(1)random.randint(low, hight) -> 返回一个位于[low,hight]之间的整数
该函数接受两个参数,这两个参数必须是整数(或者小数位是0的浮点数),并且第一个参数必须不大于第二个参数

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

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

>>> random.random()
0.9983625479554628

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

>>> random.uniform(1,5.0)
2.917249424176132
>>> random.uniform(9.9, 2)
3.4288029275359024

生成随机数组
下边我们用random.randint来生成一个随机数组

import random
def random_int_list(start, stop, length):
  start, stop = (int(start), int(stop)) if start <= stop else (int(stop), int(start))
  length = int(abs(length)) if length else 0
  random_list = []  
  for i in range(length):
   random_list.append(random.randint(start, stop))
  return random_list
接下来我们就可以用这个函数来生成一个随机的整数序列了   
>>> random_int_list(1,100,10)[54, 13, 6, 89, 87, 39, 60, 2, 63, 61]

2、使用numpy.rando模块来生成随机数组

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

import numpy as np
>>> np.random.rand(10)
array([ 0.56911206, 0.99777291, 0.18943144, 0.19387287, 0.75090637, 0.18692814, 0.69804514, 0.48808425, 0.79440667, 0.66959075])

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

>>> np.random.randn(10)
array([-1.6765704 , 0.66361856, 0.04029481, 1.19965741, -0.57514593,-0.79603968, 1.52261545, -2.17401814, 0.86671727, -1.17945975])

(3)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])

以上是python随机生成数组的方法的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. python生成随机数的方法
  2. 用python生成随机密码的方法

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

python 随机生成

上一篇:更换python默认编辑器背景色的方法

下一篇:python有哪些小练习案例

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》