Additional building blocks, recipes, and routines for working with Python iterables beyond itertools.
—
Functions for generating random selections and samples from combinatorial spaces.
Functions for generating random elements from combinatorial spaces.
def random_product(*iterables: Iterable[Any], repeat: int = 1) -> tuple[Any, ...]: ...
def random_permutation(iterable: Iterable[Any], r: int = None) -> tuple[Any, ...]: ...
def random_combination(iterable: Iterable[Any], r: int) -> tuple[Any, ...]: ...
def random_combination_with_replacement(iterable: Iterable[Any], r: int) -> tuple[Any, ...]: ...Usage:
from more_itertools import random_product, random_permutation, random_combination
# Generate random Cartesian product element
pools = ['ABC', '123']
rand_prod = random_product(*pools) # e.g., ('B', '3')
# Generate random permutation
data = 'ABCDE'
rand_perm = random_permutation(data, 3) # e.g., ('D', 'A', 'C')
# Generate random combination
rand_combo = random_combination(data, 3) # e.g., ('A', 'C', 'E')
# Generate random combination with replacement
rand_combo_repl = random_combination_with_replacement(data, 3) # e.g., ('A', 'A', 'D')Functions for sampling elements from iterables.
def sample(iterable: Iterable[Any], k: int, *, counts: Iterable[int] = None) -> list[Any]: ...Usage:
from more_itertools import sample
# Sample k elements from iterable
data = range(100)
sampled = sample(data, 5) # e.g., [23, 7, 45, 12, 89]
# Sample with weights (counts)
items = ['A', 'B', 'C']
weights = [1, 3, 2] # B is 3x more likely than A
weighted_sample = sample(items, 10, counts=weights)
# e.g., ['B', 'C', 'B', 'A', 'B', 'C', 'B', 'B', 'C', 'B']Install with Tessl CLI
npx tessl i tessl/pypi-more-itertools