我需要写一个加权版本的random.choice(列表中的每个元素被选择的可能性都不同)。这是我想出的:
def weightedChoice(choices):
"""Like random.choice, but each element can have a different chance of
being selected.
choices can be any iterable containing iterables with two items each.
Technically, they can have more than two items, the rest will just be
ignored. The first item is the thing being chosen, the second item is
its weight. The weights can be any numeric values, what matters is the
relative differences between them.
"""
space = {}
current = 0
for choice, weight in choices:
if weight > 0:
space[current] = choice
current += weight
rand = random.uniform(0, current)
for key in sorted(space.keys() + [current]):
if rand < key:
return choice
choice = space[key]
return None
对于我来说,此功能似乎过于复杂且难看。我希望这里的每个人都可以提出一些改进建议或其他替代方法。对于我来说,效率并不像代码的清洁度和可读性那么重要。
random.choices
单个呼叫要慢一个数量级。如果您需要大量随机结果,那么通过调整立即选择所有结果非常重要number_of_items_to_pick
。如果这样做,则速度要快一个数量级。