如何在 python 中使用随机函数分配更多

how to distribute more ones using random function in python

我想制作一个包含值“1”而不是其他随机数的列表。

假设我希望 60% 的“1”出现在 10 个元素中。 所以 6 个 1 元素和 4 个随机元素。 这是我的方法。

import numpy as np
import random

# to avoid generating 1s..
list_60 = np.random.randint(2,11, 10) 

array([ 6,  2,  8,  6,  6,  3,  5, 10,  6,  8])


count = 0
percentage = int(len(list_60)*(0.6) + 0.5)
for i in range(0,len(list_60)):
    if count < percentage:
        list_60[i]=0
    count += 1

list_60
array([ 1,  1,  1,  1,  1,  1,  5, 10,  6,  8])


random.shuffle(list_60)
array([ 1,  1,  1,  6,  1,  5,  1,  1,  8, 10])

程序步骤:

  1. 创建从 2 到 10 的随机数。
  2. 循环每个元素并基于百分比。并将元素更改为 1s.
  3. 随机播放列表以获得更多变化。

我不认为这是生成更多 1 的明智方法。有没有 fancy/smart 创建加权随机性的方法?

如有任何帮助,我们将不胜感激。

您可以获得索引的随机子集,然后将这些索引设置为 1:

import numpy as np

arr = np.random.randint(2, 11, 10)
index = np.random.choice(len(arr), int(len(arr) * 0.6), replace=False)
arr[index] = 1

print(arr)

你也可以在没有 numpy 的情况下这样做:

import random

arr = [random.randint(2, 11) for _ in range(10)]
index = random.sample(range(len(arr)), int(len(arr) * 0.6))
for i in index:
    arr[i] = 1

print(arr)

以上两个实现使用了10+6个随机位。从技术上讲,您只需要 4 + 4(随机数为 4,它们的随机位置为 4(感谢@KellyBundy 注意到了这一点)。您可以在 numpy 中实现此目的:

import numpy as np

arr = np.ones(10)
index = np.random.choice(len(arr), int(len(arr) * 0.4), replace=False)
arr[index] = np.random.randint(2, 11, len(index))

print(arr)

或者更简单地使用普通 python:

import random

arr = [1] * 10
for i in random.sample(range(len(arr)), int(len(arr) * 0.4)):
    arr[i] = random.randint(2, 11)

print(arr)