欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

Python随机数random模块详解及实例

程序员文章站 2022-03-25 14:44:25
...
本文给大家分享的是Python随机数random模块的几个常用的方法,非常的简单,小伙伴们喜欢的话,后续继续深入探讨

">

random 模块是Python自带的模块,除了生成最简单的随机数以外,还有很多功能。

random.random()

用来生成一个0~1之间的随机浮点数,范围[0,10

>>> import random
>>> random.random()
0.5038461831828231

random.uniform(a,b)

返回a,b之间的随机浮点数,范围[a,b]或[a,b),取决于四舍五入,a不一定要比b小。

>>> random.uniform(50,100)
76.81733455677832
>>> random.uniform(100,50)
52.98730193316595

random.randint(a,b)

返回a,b之间的整数,范围[a,b],注意:传入参数必须是整数,a一定要比b小

>>> random.randint(50,100)
54
>>> random.randint(100,50)

Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
random.randint(100,50)
File "C:\Python27\lib\random.py", line 242, in randint
return self.randrange(a, b+1)
File "C:\Python27\lib\random.py", line 218, in randrange
raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop, width)
ValueError: empty range for randrange() (100,51, -49)
>>> random.randint(50.5,100.6)

Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
random.randint(50.5,100.6)
File "C:\Python27\lib\random.py", line 242, in randint
return self.randrange(a, b+1)
File "C:\Python27\lib\random.py", line 187, in randrange
raise ValueError, "non-integer arg 1 for randrange()"
ValueError: non-integer arg 1 for randrange()

random.randrang([start], stop[, step])

返回有个区间内的整数,可以设置step。只能传入整数,random.randrange(10, 100, 2),结果相当于从[10, 12, 14, 16, … 96, 98]序列中获取一个随机数。

>>> random.randrange(100)
58
>>> random.randrange(10,100,2)
54

random.choice(sequence)

从序列中随机获取一个元素,list, tuple, 字符串都属于sequence。这里的sequence 需要是有序类型。random.randrange(10,100,2)在结果上与 random.choice(range(10,100,2) 等效。

>>> random.choice(("stone","scissors","paper"))
'stone'
>>> random.choice(["stone","scissors","paper"])
'scissors'
>>> random.choice("Random")
'm'

random.shuffle(x[,random])

用于将列表中的元素打乱,俗称为洗牌。会修改原有序列。

>>> poker = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]
>>> random.shuffle(poker)
>>> poker
['4', '10', '8', '3', 'J', '6', '2', '7', '9', 'Q', '5', 'K', 'A']

random.sample(sequence,k)

从指定序列中随机获取k个元素作为一个片段返回,sample函数不会修改原有序列。

>>> poker = ["A","2","3","4","5","6","7","8","9","10","J","Q","K"]
>>> random.sample(poker,5)
['4', '3', '10', '2', 'Q']

上述几个方式是Python常用的一些方法,但是关于随机数还有很多的故事。下回分解~

以上就是Python随机数random模块详解及实例的详细内容,更多请关注其它相关文章!

相关标签: Python random模块