3

I'm making an RPG loot generator, and I'm trying to make a random choice with weights for each rarity of items. How do I do that?

Item_rarity = ["Common", "Uncommon", "Superior", "Rare", "Legendary"]
Rarity_choice = random.choice(Item_rarity)

I expect that Common = 50%; Uncommon = 30%; Superior = 14%; Rare = 5%; Legendary = 1%. How do I do that?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
RATO
  • 45
  • 6
  • https://stackoverflow.com/questions/58346227/generating-a-random-list-from-a-tuple-but-being-able-to-select-percentage-of-eac/58346306#58346306 – Mr_U4913 Oct 18 '19 at 17:20
  • Another duplicate (more suitable IMO): [A weighted version of random.choice](https://stackoverflow.com/q/3679694/4518341) – wjandrea Oct 18 '19 at 17:32

2 Answers2

5

Use random.choices:

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

Return a k sized list of elements chosen from the population with replacement.

If a weights sequence is specified, selections are made according to the relative weights.

import random

item_rarity = ["Common", "Uncommon", "Superior", "Rare", "Legendary"]
weights = [50, 30, 14, 5, 1]

print(random.choices(item_rarity, weights)[0])
# 'Common'

Note that it returns a list, even if you just want one item, hence the [0] to get the one item in the list.

Thierry Lathuille
  • 23,663
  • 10
  • 44
  • 50
0

Not the most efficient, but general purpose.

Here we get a list from a dict of {'thing':how_many_times}:

import random

def listProb(adcit):
    res=[]
    for k,v in adcit.items():
        for occur in range(v):
            res.append(k)
    return res

Item_rarity = listProb({'common':50, 'uncommon':30,})
print(Item_rarity)

Rarity_choice = random.choice(Item_rarity)
print(Rarity_choice)

and get something like

['common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'common', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon', 'uncommon']
uncommon
shanecandoit
  • 581
  • 1
  • 3
  • 11