Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Python trick: weighted random choice from arbitrary string

I wrote a crazy python snippet I wanted to share. Due to the wonders of the very high-level python language, this works in a mostly-straightforward way:

import random
choices = ["choice1","second","final"]
weight_string="20,80"
weights=[int(i) for i in weight_string.split(",")][0:len(choices)]+[0]*(len(choices)-len(weight_string.split(",")))
weighted_choice = random.choices(population=choices,weights=weights,k=1)[0]

What this does, in the most pythonic way possible, is for each entry in weight_string when split by commas, combined with a list (array) of zeroes that is as long as the number of the choices minus the number of entries of weight_string when split by commas. And only grab the first so many of them, equal to the number of choices.

Adding the [0]*(length) provides empty values in case the weight string does not have enough entries to match the number of choices.

This logic is entirely my own. After an Internet search revealed the existence of random.choices and its interface, I assembled the weights definition without any other existing textual reference.

Comments