赞
踩
random.choices
是Python标准库中random
模块提供的一个函数,用于从给定的序列中随机选择一个值。这个函数可以用于实现随机抽样、按照概率进行选择等功能。
random.choices(population, weights=None, *, cum_weights=None, k=1)
函数的参数解释如下:
population
:必需参数,指定要进行选择的序列(可以是列表、元组等)。weights
:可选参数,指定每个元素的权重(概率)。如果不指定,则默认每个元素的权重相等。cum_weights
:可选参数,指定累计权重。如果指定了cum_weights
,则必需省略weights
参数。k
:可选参数,指定要选择的元素个数。默认为1,即只选择一个元素。- import random
-
- fruits = ['apple', 'banana', 'orange', 'grape', 'watermelon']
- chosen_fruit = random.choices(fruits)
- print(chosen_fruit)
'运行
运行结果
['grape']
- import random
-
- fruits = ['apple', 'banana', 'orange', 'grape', 'watermelon']
- weights = [0.1, 0.2, 0.3, 0.2, 0.2]
- chosen_fruit = random.choices(fruits, weights=weights)
- print(chosen_fruit)
'运行
运行结果
['orange']
- import random
-
- fruits = ['apple', 'banana', 'orange', 'grape', 'watermelon']
- chosen_fruits = random.choices(fruits, k=3)
- print(chosen_fruits)
'运行
运行结果
['banana', 'apple', 'watermelon']
- import random
-
- fruits = ['apple', 'banana', 'orange', 'grape', 'watermelon']
- cum_weights = [0.1, 0.4, 0.7, 0.9, 1.0]
- chosen_fruit = random.choices(fruits, cum_weights=cum_weights)
- print(chosen_fruit)
'运行
运行结果
['grape']
- import random
-
- fruits = ['apple', 'banana', 'orange', 'grape', 'watermelon']
- chosen_fruits = random.choices(fruits, k=1000)
- fruit_counts = {}
-
- for fruit in chosen_fruits:
- if fruit in fruit_counts:
- fruit_counts[fruit] += 1
- else:
- fruit_counts[fruit] = 1
-
- print(fruit_counts)
'运行
运行结果
{'orange': 334, 'grape': 192, 'apple': 203, 'watermelon': 152, 'banana': 119}
random.choices
函数是Python中一个非常有用的函数,可以用于实现随机抽样、按照概率进行选择等功能。通过合理地使用参数,我们可以根据需求选择单个或多个元素,并可以对选择的元素进行计数等操作。
通过阅读本文,你应该对random.choices
函数有了更深入的理解,并可以灵活地将其应用于自己的编程任务中。
random.choices 在 k>1 时,也就是选择的元素个数大于1时,元素是有可能重复的。要想得到一个不重复的随机数列,请自行编写方法。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。