python生成随机数组【转】
来源:互联网 发布:淘宝服装平铺后期教程 编辑:程序博客网 时间:2024/06/06 19:19
一、使用random模块生成随机数组
python的random模块中有一些生成随机数字的方法,例如random.randint, random.random, random.uniform, random.randrange,这些函数大同小异,均是在返回指定范围内的一个整数或浮点数,下边简单解释一下这几个函数。
1、random.randint(low, hight) -> 返回一个位于[low,hight]之间的整数
该函数接受两个参数,这两个参数必须是整数(或者小数位是0的浮点数),并且第一个参数必须不大于第二个参数
2、random.random() -> 不接受参数,返回一个[0.0, 1.0)之间的浮点数
3、random.uniform(val1, val2) -> 接受两个数字参数,返回两个数字区间的一个浮点数,不要求val1小于等于val2
5、生成随机数组
下边用random.randint来生成一个随机数组
import randomdef 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
6、生成不重复的随机数组
random.sample的函数原型为:random.sample(sequence, k),从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] slice = random.sample(list, 5) #从list中随机获取5个元素,作为一个片断返回 print slice print list #原有序列并没有改变
二、使用numpy.random模块来生成随机数组
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.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)4
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])
- python生成随机数组【转】
- python生成随机数组
- python 用numpy生成多维随机数组
- 高效生成随机数组
- 生成随机二维数组
- 算法--生成随机数组
- 随机生成数组
- 随机数组生成
- 随机数组生成算法
- numpy生成随机数组
- 生成随机数组
- 生成随机数组-php
- js随机生成数组
- python随机生成字符串
- python随机密码生成
- python 生成随机字符串
- python随机生成字符串
- python 矩阵随机生成
- window下安装gensim
- form转json方法
- 设计模式
- # 在宏定义中的使用
- laravel获取路由参数
- python生成随机数组【转】
- 转载 Matlab——zeros函数和ones函数
- Nginx.conf 配置文件标准配置(删除不必要的注释,更清晰)
- WPS Excel表格条件格式在哪如何使用以大于500的数字飘红加粗为例
- Dubbo无法发布被事务代理的Service问题
- SpringBoot配置属性之DataSource(三)
- 欢迎使用CSDN-markdown编辑器
- Spring源码深度解析 带标签
- java实现数据结构之单向链表