Python随机数生成方法
2018-03-09 22:08
726 查看
1. random.seed(int)
给随机数对象一个种子值,用于产生随机序列。对于同一个种子值的输入,之后产生的随机数序列也一样。
通常是把时间秒数等变化值作为种子值,达到每次运行产生的随机系列都不一样
seed() 省略参数,意味着使用当前系统时间生成随机数
2. random.randint(a,b)
返回指定范围的一个随机整数,包含上下限3. random.uniform(u,sigma)
随机正态浮点数4. random.randrange(start,stop,step)
按步长随机在上下限范围内取一个随机数5. random.random()
随机浮点数6. 随机选择字符
随机的选取n个字符7.random.shuffle
对list列表随机打乱顺序,也就是洗牌shuffle只作用于list,对Str会报错比如‘abcdfed’,而['1','2','3','5','6','7']可以
>>> import random
>>> random.randint(0,99)
21随机选取0到100间的偶数:
>>> import random
>>> random.randrange(0, 101, 2)
42随机浮点数:
>>> import random
>>> random.random()
0.85415370477785668
>>> random.uniform(1, 10)
5.4221167969800881随机字符:
>>> import random
>>> random.choice('abcdefg%^*f')
'd'多个字符中选取特定数量的字符:
>>> import random
random.sample('abcdefghij',3)
['a', 'd', 'b']多个字符中选取特定数量的字符组成新字符串:
>>> import random
>>> import string
>>> string.join(random.sample(['a','b','c','d','e','f','g','h','i','j'], 3)).r
eplace(" ","")
'fih'随机选取字符串:
>>> import random
>>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )
'lemon'洗牌:
>>> import random
>>> items = [1, 2, 3, 4, 5, 6]
>>> random.shuffle(items)
>>> items
[3, 2, 5, 6, 4, 1]
二、使用numpy.random模块来生成随机数组
1、np.random.rand 用于生成[0.0, 1.0)之间的随机浮点数, 当没有参数时,返回一个随机浮点数,当有一个参数时,返回该参数长度大小的一维随机浮点数数组,参数建议是整数型,因为未来版本的numpy可能不支持非整形参数。1 import numpy as np 2 >>> np.random.rand(10) 3 array([ 0.56911206, 0.99777291, 0.18943144, 0.19387287, 0.75090637, 4 0.18692814, 0.69804514, 0.48808425, 0.79440667, 0.66959075])当然该函数还可以用于生成多维数组,这里不做详述。2、np.random.randn该函数返回一个样本,具有标准正态分布。
1 >>> np.random.randn(10) 2 array([-1.6765704 , 0.66361856, 0.04029481, 1.19965741, -0.57514593, 3 -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) 45、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 seed() 函数&numpy &scikit-learn随机数据生成
- python生成不重复随机数和对list乱序的解决方法
- Python生成随机数的方法
- Python生成随机数的方法【转载】
- python生成随机数方法小结
- Python生成随机数的方法
- python之随机数生成方法汇总
- python生成随机数方法小结
- Python 随机数生成的几种方法
- python 生成随机数的方法
- Python生成随机数的方法
- Python生成随机数的方法
- Python 生成 -1~1 之间的随机数矩阵方法
- Python简单生成随机数的方法示例
- Python生成随机数的方法
- Python生成随机数的方法
- Python生成随机数的方法
- Python生成随机数的方法