Python Glossary Русский

Python 3.6+randomterm

random.choices

selection

Returns a list of k random items chosen with replacement. Weights are supported (weights or cum_weights).

Syntax

random.choices(population, weights=None, k=1)

Sampling is done with replacement, so duplicates are expected and k may freely exceed the size of population; when the items must be distinct, use sample. Weights are relative and are not normalised to 1, but their count must match population or you get a ValueError. The cumulative weight table is rebuilt on every call, so for many draws with the same weights it is cheaper to compute it once yourself and pass cum_weights.

Examples

import random
random.seed(42)
print(random.choices([1,2,3,4,5], k=3))  # → 3 элемента
print(random.choices('abc', weights=[1,2,3], k=5))  # → с весами
print(random.choices(['H','T'], k=10))  # → монета
results = random.choices(range(1,7), k=1000)
from collections import Counter
print(Counter(results).most_common(3))  # → топ-3
print(random.choices(['red','green'], weights=[1,9], k=5))

See also

Open in the full glossarydocs.python.orgReport an inaccuracy