Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何生成特定值出现率为5%的随机数列表?_Python_Python 3.x - Fatal编程技术网

Python 如何生成特定值出现率为5%的随机数列表?

Python 如何生成特定值出现率为5%的随机数列表?,python,python-3.x,Python,Python 3.x,我需要生成一个包含100个随机整数的列表。但是,我需要以这样的方式创建值:只有5%的情况下才会出现较大的值,而其余的值等于0 我就是这样生成这样的列表的。我如何指定5%的情况下会出现较大的值(即180000左右) import random random.sample(range(0, 180000), 100) 例如: [0, 0, 0, 0, 0, 155000, 0, 0, 0, 0, 0, 0, 0, 0,...,0, 0, 170000] 您可以这样做: import numpy

我需要生成一个包含100个随机整数的列表。但是,我需要以这样的方式创建值:只有5%的情况下才会出现较大的值,而其余的值等于0

我就是这样生成这样的列表的。我如何指定5%的情况下会出现较大的值(即180000左右)

import random
random.sample(range(0, 180000), 100)
例如:

[0, 0, 0, 0, 0, 155000, 0, 0, 0, 0, 0, 0, 0, 0,...,0, 0, 170000] 

您可以这样做:

import numpy as np

nb_vals = 100
large_values = np.arange(150000, 180000, 5000) # from 150 000 to 180 000 by 5 000 steps
your_list = [
    0 if np.random.rand() < 0.95 # 95% chance of 0
    else np.random.choice(large_values) # 5% chance of random element from large_values
    for _ in range(nb_vals) # nb_val independant draws
]

您可以这样做:

import numpy as np

nb_vals = 100
large_values = np.arange(150000, 180000, 5000) # from 150 000 to 180 000 by 5 000 steps
your_list = [
    0 if np.random.rand() < 0.95 # 95% chance of 0
    else np.random.choice(large_values) # 5% chance of random element from large_values
    for _ in range(nb_vals) # nb_val independant draws
]

大数值是什么意思?大于0?平均5%或5%。@OlivierMelançon:正好5%@Selcuk:我指的是m示例中显示的数值。大数值是什么意思?大于0?平均5%或5%。@OlivierMelançon:正好5%@Selcuk:我指的是m示例中显示的数值。