Python随机数

“Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin.”

John von Neumann, 1951

Python中自带了随机数的模块random,它们编程当前往往是十分重要的。下面对random模块进行介绍。

random模块

  1. randint()
  2. random()
  3. uniform()
  4. randrange()
  5. choice()
  6. sample()

randint()

randint(a, b)用于生成随机的整数[a, b]。需要2个参数,分别指定随机数的上限和下限。

NB:此处包含上限和下限的值。

>>> random.randint(1, 10)
6
>>> random.randint(1, 10)
3
>>> random.randint(1, 10)
4
>>> random.randint(1, 10)
10
>>>

random()

random()用于生成随机的(0.0, 1.0)浮点数。

>>> random.random()
0.8135945944158621
>>> random.random()
0.10820684120770308
>>> random.random()
0.8036909615265496
>>> 

uniform()

uniform(a, b)用于生成随机的[a, b]或者[b, a]浮点数。需要2个参数,分别指定随机数的上限和下限。而无论两者的大小。

>>> random.uniform(1, 10)
9.877878726666212
>>> random.uniform(1, 10)
7.320900049560443
>>> random.uniform(10, 1)
9.26225787417653
>>>

randrange()

randrange(stop),randrange(start, stop[, step])用于返回相当于使用range(stop)或者range(start, stop[, step])生成列表的随机一项的值。

>>> random.randrange(10)
1
>>> random.randrange(10)
9
>>> random.randrange(1, 10, 2)
3
>>> random.randrange(1, 10, 2)
3
>>> random.randrange(1, 10, 2)
9
>>>

choice()

choice(seq)随机返回序列seq中的一项。

>>> random.choice("!@#$%^&*()_+")
'_'
>>> random.choice("!@#$%^&*()_+")
'+'
>>> random.choice([1, 2, 3, 4])
3
>>> random.choice([1, 2, 3, 4])
1
>>>

sample()

sample(population, k)返回一个包含k个元素的列表,列表元素取自序列或者集合population,且列表元素唯一。

>>> random.sample([1, 2, 3, 4], 2)
[4, 2]
>>> random.sample([1, 2, 3, 4], 2)
[1, 2]
>>> random.sample("!@#$%^&*()_+", 3)
['^', '&', '_']
>>> random.sample("!@#$%^&*()_+", 3)
[')', '#', '^']
>>> 

更多请参考Python标准库

原文地址:https://www.cnblogs.com/furzoom/p/7710293.html