选择具有重量的随机项目

xra*_*alf 8 python random

我有一个大约的列表.10000件物品.目前的情况是每个项目都有相关的权重(优先级或重要性).现在最小的重量是-100(负值和零值可以去除),最高权重是1500.体重由人们的直觉决定(人们如何认为该项目对社区很重要).因为要确定最重要的项目并不容易,所以我想使用一些随机因素,这样重量较轻的物品选择的机会就会减少,而且将来会调整它们的重量(常识和随机性).

你知道如何编写一个函数getItem吗?

def getItem(dict):
  # this function should return random item from 
  # the dictionary of item-weight pairs (or list of tuples)
  # Normally I would return only random item from the dictionary,
  # but now I'd like to have this: The item with weight 1500 should
  # have much more chance to be returned than the item with weight 10.
  # What's my idea is to sum up the weights of all items and then compute
  # some ratios. But maybe you have better idea.
  return randomItem
Run Code Online (Sandbox Code Playgroud)

谢谢

Bog*_*dan 13

看看这个,我认为这是你需要的,不同的方法在Python中加权随机生成之间的一些很好的比较

最简单的方法是:

import random

def weighted_choice(weights):
    totals = []
    running_total = 0

    for w in weights:
        running_total += w
        totals.append(running_total)

    rnd = random.random() * running_total
    for i, total in enumerate(totals):
        if rnd < total:
            return i
Run Code Online (Sandbox Code Playgroud)

您可以在上面的链接中找到更多详细信息和可能的改进以及一些不同的方法.


m.e*_*ahi 6

Python 3.6引入了random.choices()

def get_item(items, items_weights):
    return random.choices(items, weights=items_weights)[0]
Run Code Online (Sandbox Code Playgroud)