本文摘自php中文网,作者不言,侵删。
本篇文章给大家带来的内容是关于Python中random模块生成随机数的七个常用函数的用法介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
Python中的random模块用于生成随机数。
使用该模块之前需要 import random
几个常用的函数用法:
1、random.random
函数原型:
用于生成一个0到1的随机符点数: 0 <= n < 1.0
1 | >>> random.random()0.5578093677010638
|
2、random.uniform
函数原型:
用于生成一个指定范围内的随机符点数,两个参数其中一个是上限,一个是下限。如果a > b,则生成的随机数n: b <= n <= a。如果 a <b, 则 a <= n <= b。
1 2 3 4 | >>> random.uniform(10, 20)
16.864972616523794
>>> random.uniform(20, 10)
10.851664722380086
|
3、random.randint
函数原型:
用于生成一个指定范围内的整数。其中参数a是下限,参数b是上限,生成的随机数n: a <= n <= b。
1 2 3 4 5 6 7 8 9 | >>> random.randint(12, 20)
>>> random.randint(20, 20)
>>> random.randint(30, 20) # 不能这样用,下限必须小于等于上限
Traceback (most recent call last):
File "<input>" , line 1, in <module>
File "D:\Software\Anaconda3\lib\random.py" , line 221, in randint
return self.randrange(a, b+1)
File "D:\Software\Anaconda3\lib\random.py" , line 199, in randrange
raise ValueError( "empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
|
4、random.randrange
函数原型:
1 | random.randrange([start], stop[, step])
|
从指定范围内,按指定基数递增的集合中获取一个随机数。如:random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, … 96, 98]序列中获取一个随机数。random.randrange(10, 100, 2)在结果上与 random.choice(range(10, 100, 2) 等效。
1 2 3 4 | >>> random.randrange(10, 100)
29
>>> random.randrange(10, 100, 2)
98
|
5、random.choice
函数原型:
从序列中获取一个随机元素。其中,参数sequence表示一个有序类型。注意:sequence在python不是一种特定的类型,而是泛指一系列的类型。list, tuple, 字符串都属于sequence。
1 2 3 4 5 6 | >>> random.choice( 'HelloWorld' )
'r'
>>> random.choice([ 'java' , 'python' , 'C' , 'PHP' ])
'python'
>>> random.choice(( 'list' , 'tuple' , 'dict' ))
'tuple'
|
6、random.shuffle
函数原型:
1 | random.shuffle(x[, random])
|
用于将一个列表中的元素打乱。
1 2 3 4 | >>> l = [ 'java' , 'python' , 'C' , 'PHP' ]
>>> random.shuffle(l)
>>> l
[ 'PHP' , 'C' , 'java' , 'python' ]
|
7、random.sample
函数原型:
1 | random.sample(sequence, k)
|
从指定序列中随机获取指定长度的片断。sample函数不会修改原有序列。
1 2 | >>> random.sample([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 5)
[7, 2, 9, 4, 1]
|
以上就是Python中random模块生成随机数的七个常用函数的用法介绍的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python中range函数用法是什么
Python的注释有哪几种
在Python中如何获取字符串的长度
Python的str强转int时遇到的问题
Python中什么是对象
Python怎么导入图片资源
在 Python 中如何得到对象的所有属性
Python如何读取excel文件
Python装饰器的深入浅出
Python中如何用django连接数据库(图文)
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python中random模块生成随机数的七个常用函数的用法介绍