您当前的位置: 首页 >  Python

IT之一小佬

暂无认证

  • 0浏览

    0关注

    1192博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

IT之一小佬 发布时间:2022-04-10 00:23:32 ,浏览量:0

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

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

s = random.random()
s

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

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

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

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

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

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

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

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

 

 

6、 random.choices(sequence, weights=None, cum_weights=None, k=1)
  • choices()方法返回一个列表,其中包含从指定序列中随机选择的元素。
  • 可以使用weights参数或cum_weights参数权衡每个结果的可能性。
  • 序列可以是字符串、范围、列表、元组或任何其他类型的序列。
ParameterDescriptionsequenceRequired. A sequence like a list, a tuple, a range of numbers etc.weightsOptional. A list were you can weigh the possibility for each value. Default Nonecum_weightsOptional. 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 NonekOptional. 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))

运行结果:

关注
打赏
1665675218
查看更多评论
立即登录/注册

微信扫码登录

0.0480s