使用python生成随机数(random模块)
  TEZNKK3IfmPf 2023年11月14日 20 0

在 Python 中用于生成随机数的模块是 random,在使用前需要 import.

1、random.random():生成一个 0-1 之间的随机浮点数

import random

s = random.random()
s

使用python生成随机数(random模块)

2、random.uniform(a, b):生成[a,b]之间的浮点数

import random

a = 3.0
b = 6.0
s = random.uniform(a, b)
s

使用python生成随机数(random模块)

使用python生成随机数(random模块)

3、random.randint(a, b):生成[a,b]之间的整数

import random

a = 3
b = 6
s = random.randint(a, b)
s

使用python生成随机数(random模块)

4、random.randrange(a, b, step):在指定的集合[a,b)中,以 step 为基数随机取一个数

import random

a = 3
b = 25
s = random.randrange(a, b, 6)
s

使用python生成随机数(random模块)

5、random.choice(sequence):从特定序列中随机取一个元素,这里的序列可以是字符串,列表, 元组等

import random

a = '我爱你中国'
s = random.choice(a)
s

使用python生成随机数(random模块)

 使用python生成随机数(random模块)

 使用python生成随机数(random模块)

6、 random.choices(sequence, weights=None, cum_weights=None, k=1)

  • choices()方法返回一个列表,其中包含从指定序列中随机选择的元素。
  • 可以使用weights参数或cum_weights参数权衡每个结果的可能性。
  • 序列可以是字符串、范围、列表、元组或任何其他类型的序列。
Parameter Description
sequence Required. A sequence like a list, a tuple, a range of numbers etc.
weights Optional. A list were you can weigh the possibility for each value.
Default None
cum_weights Optional. A list were you can weigh the possibility for each value, only this time the possibility is accumulated.
Example: normal weights list: [2, 1, 1] is the same as this cum_weights list; [2, 3, 4].
Default None
k Optional. An integer defining the length of the returned list

示例代码:

import random

my_list = ["AAA", "BBB", "CCC"]

print(random.choice(my_list))
print(random.choices(my_list))
print(random.choices(my_list, weights=[3, 2, 1], k=10))

运行结果:

使用python生成随机数(random模块)

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月31日   32   0   0 python开发语言
  TEZNKK3IfmPf   2024年05月31日   25   0   0 python
  TEZNKK3IfmPf   2024年05月31日   34   0   0 excelpython
  TEZNKK3IfmPf   2024年05月31日   25   0   0 python
TEZNKK3IfmPf