[英]generate random sample with in a range but with different size each time in python
Ex: Assume we have [1,2,3,4,5,6,7,8,9,10,11,12,13]
for the first sample we will select [3, 4, 5, 9, 1, 2]
and for the second sample [7, 9, 1, 4, 5, 6, 2]
and so on Make sure each sample will have at least 3 elements例如:假设我们有
[1,2,3,4,5,6,7,8,9,10,11,12,13]
作为第一个样本,我们将 select [3, 4, 5, 9, 1, 2]
和第二个样本[7, 9, 1, 4, 5, 6, 2]
等等 确保每个样本至少有 3 个元素
With that said:照这样说:
import random
def select_sample(arr,minsize):
size = random.randrange(minsize,len(arr))
return [random.choice(arr) for i in range(size)]
Consider utilizing random.
sample
考虑使用
random. sample
: random. sample
random. sample
:
from random import sample
def generate_n_samples_different_sizes(population: list, min_sample_size: int,
num_samples: int) -> list[list[int]]:
pop_size = len(population)
sample_sizes = sample(range(min_sample_size, pop_size + 1), k=num_samples)
return [
sample(population, k=sample_size)
for sample_size in sorted(sample_sizes) # removed sorted if increasing sample sizes is not required
]
n_samples_different_sizes = generate_n_samples_different_sizes(
population=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13],
min_sample_size=3,
num_samples=4)
print(n_samples_different_sizes)
Example Output:示例 Output:
[[7, 1, 10], [7, 11, 5, 6, 12], [6, 9, 8, 1, 10, 5, 4, 3, 2, 11, 13, 7], [2, 12, 8, 4, 10, 5, 11, 6, 7, 1, 3, 9, 13]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.