I want to create a fishing game. Whenever the player press a button, the game will return a fish. Every fish has a percentage ( small fish , 45% ; medium fish, 25% ; big, 15%; huge, 4.9%; shark,0.1).
fish_size = [("small",45),("medium",25),("big",15),("huge",4.9),("shark",0.1)]
How can I get a fish randomly from this list by percentage?
Advertisement
Answer
If you have a list of elements to choose from (in your case, the fish types), and a list of the weights (does not have to be normalised to 1
or 100%), you can use the choices
method of the random
built-in package. See its documentation for more detail.
An example:
>>> import random >>> fish = ['small', 'medium', 'big', 'huge', 'shark'] >>> weights = [45, 25, 15, 4.9, 0.1] >>> random.choices(fish, weights)[0] 'medium'
Note that you can use choices
to return multiple elements (using the optional k
keyword argument). Therefore, choices
returns a list. By default, k=1
, so only one value is returned in the list. Adding [0]
to the end of the function call automatically extracts this value from the list.