增加/减少随机模块的机会

Increasing / decrasing chance on random module

例如我正在编写一个游戏。我需要点钱 。箱子是免费的,但钥匙是付费的。我怎样才能增加 key needed premium chest 的几率以及我怎样才能完全降低 的几率免费高级宝箱

import random 

list1 = ["fully free premium chest", "key needed premium chest", "fully free normal chest"]


random.choice(list1)

使用 random.choices 并为您的不同选项赋予权重,权重与您希望赋予每个选项的概率成正比。

Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises IndexError.

If a weights sequence is specified, selections are made according to the relative weights. Alternatively, if a cum_weights sequence is given, the selections are made according to the cumulative weights (perhaps computed using itertools.accumulate()). For example, the relative weights [10, 5, 30, 5] are equivalent to the cumulative weights [10, 15, 45, 50]. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.

例如,您可以使用权重 [10, 40, 2] 使第二个项目被选中的概率更大,最后一个项目的概率更小。

它将是:

import random 

list1 = ["fully free premium chest", "key needed premium chest", "fully free normal chest"]


random.choices(list1, weights=[10, 40, 2], k=1)[0]
# 'key needed premium chest'