首页 > 解决方案 > 在 numpy 中生成大小为 n、均值 = 20、min=2 和 max=25 的整数列表

问题描述

我想生成一个大小为 n、平均值 = 20、最小值 = 2 和最大值 = 25 的整数列表。

并尝试了下面的代码。这非常耗时。

# generate service time with mean = 20, min = 2 and max = 25
def gen_avg(n, expected_avg=20, a=2, b=25):
    while True:
        l = np.random.randint(a, b, size=n)
        avg = np.mean(l)

        if avg == expected_avg:
            return l

请帮我一些快速的方法

标签: pythonnumpy

解决方案


您可以生成一个随机列表,然后通过替换大于平均值的数字(如果当前平均值太低)或替换小于平均值的数字(如果当前平均值太高)来稍微调整数字,就像这样

def gen_avg(n, expected_avg=20, a=2, b=25):
    l = np.random.randint(a, b, size=n)
    while True:
        if np.mean(l) == expected_avg:
            break
        while np.mean(l) > expected_avg:
            c = np.random.choice(np.where(l>expected_avg)[0])
            l[c] = np.random.randint(a, expected_avg+1)
        while np.mean(l) < expected_avg:
            c = np.random.choice(np.where(l<expected_avg)[0])
            l[c] = np.random.randint(expected_avg, b)
        return l

这是假设您不关心从任何特别有趣的发行版中进行生产。


推荐阅读