在 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参数权衡每个结果的可能性。
- 序列可以是字符串、范围、列表、元组或任何其他类型的序列。
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))
运行结果: