【问题标题】:Weighted random numbers in Python from a list of valuesPython中来自值列表的加权随机数
【发布时间】:2017-05-09 17:11:10
【问题描述】:

我正在尝试创建一个包含 1 到 1000 之间的 10,000 个随机数的列表。但我希望 80-85% 的数字属于同一类别(我的意思是其中大约 100 个数字应该出现 80% 的时间在随机数列表中),其余的出现大约 15-20% 的时间。知道这是否可以在 Python/NumPy/SciPy 中完成。谢谢。

【问题讨论】:

  • 你能说得更具体点吗?这 100 个号码是连续排列的吗?
  • 没有。无论如何,它们都可以展开,但应该在 1 到 1000 之间。
  • 那你为什么需要一个特殊的函数呢?只需使用random.randint() 2 次。第一次选择这 100 个 vs 休息,下一次从中选择
  • 数字是如何分类的?

标签: python list numpy random scipy


【解决方案1】:

这是一种方法-

a = np.arange(1,1001) # Input array to extract numbers from

# Select 100 random unique numbers from input array and get also store leftovers
p1 = np.random.choice(a,size=100,replace=0)
p2 = np.setdiff1d(a,p1)

# Get random indices for indexing into p1 and p2
p1_idx = np.random.randint(0,p1.size,(8000))
p2_idx = np.random.randint(0,p2.size,(2000))

# Index and concatenate and randomize their positions
out = np.random.permutation(np.hstack((p1[p1_idx], p2[p2_idx])))

让我们在运行后验证-

In [78]: np.in1d(out, p1).sum()
Out[78]: 8000

In [79]: np.in1d(out, p2).sum()
Out[79]: 2000

【讨论】:

    【解决方案2】:

    这可以通过调用random.randint() 来选择一个列表并在正确的列表上调用random.choice() 来轻松完成。我假设列表 frequent 包含 100 个要选择的元素 80 百分比,rare 包含 900 要选择的元素 20 百分比。

    import random
    a = random.randint(1,5)
    if a == 1:
        # Case for rare numbers
        choice = random.choice(rare)
    else:
        # case for frequent numbers
        choice = random.choice(frequent)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-02
      • 2019-04-26
      • 2010-11-06
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      相关资源
      最近更新 更多