choices函数如何选择随机项目?
choices() 函数是 Python 中的一个随机模块 random 中的函数。它用于从给定的项目中进行随机选择。
该函数可以有多种使用方式,下面我将对它的使用方式进行详细说明。
1. choices(population, weights=None, k=1)
这是最基本的使用方式,其中 population 用于指定要进行选择的项目列表,weights 用于指定项目的权重列表(可以为空),k 用于指定需要选择的项目数量,默认为 1。
示例1:
import random colors = ['red', 'blue', 'green', 'yellow'] chosen_colors = random.choices(colors, k=3) print(chosen_colors)
输出结果可能为: ['blue', 'green', 'red']
示例2:
import random colors = ['red', 'blue', 'green', 'yellow'] weights = [0.1, 0.3, 0.5, 0.1] chosen_colors = random.choices(colors, weights, k=3) print(chosen_colors)
输出结果可能为: ['green', 'green', 'blue']
可以看到,当指定了权重列表时,choices() 函数会按照指定的权重进行选择。
2. choices(population, cum_weights=None, k=1)
这是另一种使用方式,其中 cum_weights 用于指定累积权重列表(可以为空)。cum_weights 列表是从权重列表得到的累积和列表,它给定了对应项目的累积权重范围。
示例:
import random colors = ['red', 'blue', 'green', 'yellow'] cum_weights = [0.1, 0.4, 0.9, 1.0] chosen_colors = random.choices(colors, cum_weights, k=3) print(chosen_colors)
输出结果可能为: ['green', 'yellow', 'blue']
此处的 cum_weights 列表可以看作是对权重列表进行累积求和后的结果。在上面的示例中,'red' 的权重为 0.1,'blue' 的权重为 0.4,'green' 的权重为 0.9,'yellow' 的权重为 1.0。choices() 函数会根据这个累积权重范围进行选择。
总结起来,choices() 函数根据权重或累积权重来进行随机选择。根据使用方式的不同,可以根据项目的权重进行选择,或者根据项目的累积权重范围进行选择。
