【问题标题】:Select random item with weight选择有重量的随机物品
【发布时间】:2012-02-13 11:49:48
【问题描述】:

我有一个大约的列表。 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

谢谢

【问题讨论】:

标签: python random


【解决方案1】:

看看这个,我认为这是你需要的,不同方法之间的一些很好的比较Weighted random generation in 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

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

【讨论】:

【解决方案2】:

Python 3.6 引入random.choices()

def get_item(items, items_weights):
    return random.choices(items, weights=items_weights)[0]

【讨论】:

  • 这正是 OP 想要的,使用一行标准 Python 库代码。谢谢!
【解决方案3】:

您应该提取一个介于 0 和权重总和(定义为正)之间的随机数。然后,您使用 bisect 从列表中获取项目:http://docs.python.org/library/bisect.html(bisect 标准模块)。

import random 
import bisect
weight = {'a':0.3,'b':3.2,'c':2.4}
items = weight.keys()
mysum = 0
breakpoints = [] 
for i in items:
    mysum += weight[i]
    breakpoints.append(mysum)

def getitem(breakpoints,items):
    score = random.random() * breakpoints[-1]
    i = bisect.bisect(breakpoints, score)
    return items[i] 

print getitem(breakpoints,items)

【讨论】:

    【解决方案4】:

    如果权重不是负数,则更容易做到。如果你必须有负权重,你必须用尽可能低的权重来抵消权重。在你的情况下,offsetted_weight = itemweight + 100

    在伪代码中是这样的:

    Calculate the sum of all the weights.
    Do a random from 0 to the sum of the weights
    Set i to 0
    While the random number > 0
        Subtract the weight of the item at index i  from random
        If the random number is < 0 return item[i]
        Add 1 to i
    

    【讨论】:

    • 负重是在每件商品的权重为1的时候开始存在的。但是没有必要有负权重,我可以去掉负数。
    【解决方案5】:

    如果您将数据存储在数据库中,则可以使用 SQL:

    SELECT * FROM table ORDER BY weight*random() DESC LIMIT 1
    

    【讨论】:

    • 整洁,但它是 SQL,并且问题用 python 标签标记。无论如何,我喜欢这个主意。
    • @copperttim 实际上我喜欢它,因为我使用sql,而且您的解决方案乍一看看起来相当不错且可用。
    • 根据您的描述,我认为您正在使用 sql。希望它能按你的需要工作。
    • 我删除了我的反对票,但您的回答似乎与我的存在相同的缺陷(正如@SvenMarnach 所指出的那样)。
    • 我也看到了,但是有瑕疵的答案在这里很适合学习。很遗憾删除它们。 warning 之前就足够了。
    猜你喜欢
    • 2019-06-07
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    相关资源
    最近更新 更多