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标准库

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

枫竹梦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值