Python - AI 助手

Python random.choices() 方法



Python random 模組中的 **random.choices()** 方法用於從序列(例如列表)中選擇元素,並可以選擇權重或累積權重。當您想從列表中隨機選擇元素,但又想根據其權重控制每個元素被選中的可能性時,此方法特別有用。

此方法提供了一種靈活的方式來為序列中的每個元素指定權重。這些權重會影響每個元素被選中的機率。權重較高的元素更有可能被選中。此外,您可以指定累積權重而不是提供單個權重。累積權重是列表中每個元素之前所有元素權重的總和。

語法

以下是 **random.choices()** 方法的語法:

random.choices(seq, weights=None, *, cum_weights=None, k=1)

引數

以下是此方法的引數:

  • **seq :** 序列資料型別(可以是列表、元組、字串或集合)。

  • **weights: ** 一個可選的列表,指定每個元素被選中的可能性。值越高,機率越高。

  • **cum_weights: ** 一個可選的累積權重列表。這些是每個元素之前所有元素權重的總和,當與 itertools.accumulate() 一起計算時可以最佳化選擇。

  • **k: ** 要從總體中選擇的元素數量。

返回值

此方法返回一個列表,其中包含從指定序列中隨機選擇的 **k** 個元素。

示例 1

以下是一個演示 python **random.choices()** 方法用法的基本示例:

import random

# Population of items
input_list = ["Italy","Germany","London","Bristol"]

# Select 3 items with equal probability
selected_items = random.choices(input_list, k=6)

print(selected_items)

執行以上程式碼時,我們得到以下輸出:

['London', 'London', 'Italy', 'Bristol', 'Italy', 'London']

示例 2

此示例使用 python **random.choices()** 方法和權重。

import random

input_list=["Italy","Germany","London","Bristol"]
output_list=random.choices(input_list,weights=[10,5,6,2],k=10)

print(output_list)

以下是程式碼的輸出:

['Bristol', 'London', 'Italy', 'London', 'London', 'Italy', 'Germany', 'Italy', 'Italy', 'Italy']

示例 3

讓我們看看此方法使用累積權重的另一個示例:

import random
from itertools import accumulate

# Population of items
input_list = ["Italy","Germany","London","Bristol"]

weights = [10, 5, 30, 10]
cum_weights = list(accumulate(weights))

# Select 4 items based on cumulative weights
selected_items = random.choices(input_list, cum_weights=cum_weights, k=8)
print(selected_items)

以下是程式碼的輸出:

['Italy', 'London', 'London', 'London', 'Bristol', 'Italy', 'Bristol', 'London']
python_modules.htm
廣告