我想做出随机选择,但要为其值赋权

RAT*_*ATO 3 python random

我正在制作一个RPG战利品生成器,并且尝试对每种稀有物品的权重进行随机选择。我怎么做?

Item_rarity = ["Common", "Uncommon", "Superior", "Rare", "Legendary"]
Rarity_choice = random.choice(Item_rarity)
Run Code Online (Sandbox Code Playgroud)

我希望Common = 50%;罕见= 30%;上等= 14%; 稀有= 5%;传奇人物= 1%。我怎么做?

Thi*_*lle 5

使用random.choices

random.choices(人口,权重=无,*,cum_weights =无,k = 1)

返回从人口中选择的具有替换的ak大小的元素列表。

如果指定了权重顺序,则根据相对权重进行选择。

import random

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

print(random.choices(item_rarity, weights)[0])
# 'Common'
Run Code Online (Sandbox Code Playgroud)

请注意,即使您只想要一个项目,它也会返回一个列表,因此[0]会获得列表中的一个项目。