python的random.choices
时间: 2023-10-14 16:05:11 浏览: 71
`random.choices()` 是 Python 中的一个函数,用于从给定的序列中随机选择元素。它接受两个参数:第一个参数是可迭代的序列,第二个参数是一个可选的权重列表或元组,用于指定每个元素被选择的概率。如果未提供权重列表,则默认情况下每个元素被选择的概率相等。
这是一个使用 `random.choices()` 的例子:
```python
import random
fruits = ['apple', 'banana', 'cherry', 'durian']
weights = [0.4, 0.3, 0.2, 0.1]
random_fruit = random.choices(fruits, weights)
print(random_fruit)
```
在这个例子中,根据权重列表 `weights` 中指定的概率,随机选择一个水果并将其打印出来。
相关问题
python random.choices
random.choices函数是Python标准库random模块中的一个函数,用于从给定的序列中随机选择元素。它可以用来实现有权重的随机选择。
函数签名如下:
random.choices(population, weights=None, *, cum_weights=None, k=1)
参数说明:
- population: 必需参数,表示要从中选择元素的序列,可以是列表、元组、字符串等可迭代对象。
- weights: 可选参数,表示每个元素的选择权重,默认为None。当weights不为None时,它必须与population的长度相同,且每个权重都是非负数。
- cum_weights: 可选参数,表示每个元素的累积权重,默认为None。当cum_weights不为None时,它必须与population的长度相同,且每个累积权重都是非负数。如果同时给定了weights和cum_weights参数,则会忽略weights参数。
- k: 可选参数,表示要选择的元素个数,默认为1。
返回值:
- 返回一个列表,包含从population中随机选择的元素。
示例用法:
```python
import random
population = ['apple', 'banana', 'cherry']
weights = [1, 2, 3]
result = random.choices(population, weights, k=5)
print(result)
```
这个例子中,根据权重选择了5个元素,可能的结果是['banana', 'cherry', 'cherry', 'banana', 'cherry']。
python random.choices 用法
random.choices() 是 Python 中 random 模块提供的一个函数,用于从给定的序列中随机选择元素。
它的语法如下:
random.choices(population, weights=None, cum_weights=None, k=1)
参数说明:
- population:必选参数,表示待选择的序列、列表或其他可迭代对象。
- weights:可选参数,表示每个元素被选择的概率,默认为 None,即每个元素被选择的概率相等。
- cum_weights:可选参数,表示累积权重列表,用于指定每个元素被选择的概率,默认为 None。
- k:可选参数,表示需要选择的元素个数,默认为 1。
返回值:
返回一个列表,包含了从序列中随机选择的元素。
示例代码:
import random
# 从列表中随机选择一个元素
fruits = ['apple', 'banana', 'melon', 'orange']
chosen_fruit = random.choices(fruits)
print(chosen_fruit) # 输出类似 ['banana']
# 从列表中随机选择两个元素
chosen_fruits = random.choices(fruits, k=2)
print(chosen_fruits) # 输出类似 ['banana', 'orange']