Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python random.choices() Method



Therandom.choices() method in Python random module is used to select elements from a sequence (like a list) with optional weights or cumulative weights. This method is particularly useful when you want to randomly select elements from a list but want to control how likely each element is to be picked over others based on their weights.

This method provides a flexible to specify weights for each element in the sequence. These weights influence the probability of each element being selected. Elements with higher weights are more likely to be chosen. Also, you can specify the cumulative weights instead of providing individual weights. Cumulative weights are the sum of the weights up to each element in the list.

Syntax

Following is the syntax ofrandom.choices() method −

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

Parameters

Following are the parameters of this method −

  • seq : Sequence data type (can be a list, tuple, string or set).

  • weights: An optional list that specifies how likely each element is to be chosen. Higher values mean higher probability.

  • cum_weights:An optional list of cumulative weights. These are sums of weights up to each element, which can optimize selection when computed with itertools.accumulate().

  • k: Number of elements to pick from the population.

Return Value

This method returns a list containingk randomly chosen elements from the specified sequence.

Example 1

Following is a basic example demonstrating the use of the pythonrandom.choices() method −

import random# Population of itemsinput_list = ["Italy","Germany","London","Bristol"]# Select 3 items with equal probabilityselected_items = random.choices(input_list, k=6)print(selected_items)

While executing the above code we get the following output −

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

Example 2

This example uses the pythonrandom.choices() method with the weights.

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

Following is the output of the code −

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

Example 3

Let's see the another example of this method with cumulative weights −

import randomfrom itertools import accumulate# Population of itemsinput_list = ["Italy","Germany","London","Bristol"]weights = [10, 5, 30, 10]cum_weights = list(accumulate(weights))# Select 4 items based on cumulative weightsselected_items = random.choices(input_list, cum_weights=cum_weights, k=8)print(selected_items)

Following is the output of the code −

['Italy', 'London', 'London', 'London', 'Bristol', 'Italy', 'Bristol', 'London']
python_modules.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp