首页 > 解决方案 > 从列表中抽取指定数量的样本。使用所有列表元素

问题描述

我有一个元素列表。现在我想指定我从这个列表中抽取的抽取/样本的数量。但是,我必须确保

(i) 所有样本一起包括所有原始元素

(ii) 每个样本的样本量不应相同

我原来的问题的一个更新

更新(iii) 最小样本量为 2

例子:

list = [1,2,3,4,5,6,7,8,9,10]
draws = 4
samples = some_function(draws,list)
set(tuple(row) for row in sample) == set(list) # must be true

samples =[[1,2,3],[4,5],[6,7,8],[9,10]]# 4 次抽取,一起包括所有元素,两种不同的样本量,最小样本量 > 2

问题:有没有一种简单的方法可以使用例如numpy.random?**

np.random.permutation这是使用and的一次尝试np.random.choice。但是,这种方法并不总是在最终样本中包含所有列表元素。

srch_list = list(range(100))
draws = 10
mid = round(len(srch_list)/draws)
n_leafs = range(mid-2,mid+3)

rnd_list = np.random.permutation(srch_list)
leafs = []
for i in range(draws):
    idx = np.random.choice(n_leafs)
    leafs.append(rnd_list[:idx])
    rnd_list = rnd_list[idx:]


标签: pythonnumpyrandom

解决方案


一种方法:

import numpy as np

np.random.seed(1)

l = [1,2,3,4,5,6,7,8,9,10]

ids = np.concatenate(([0],
                     np.random.choice(range(1, len(l)-1), 3, replace=False),
                     [len(l)]))

ids = np.sort(ids)

chunks = [l[i:j] for i,j in zip(ids[:-1], ids[1:])]

chunks
[[1, 2], [3], [4, 5, 6, 7, 8], [9, 10]]

现在,如果您还需要随机播放列表中的元素,您可以使用numpy.random.shuffle

np.random.shuffle(l)
chunks = [l[i:j] for i,j in zip(ids[:-1], ids[1:])]

chunks
[[5, 9], [3], [10, 1, 6, 8, 7], [2, 4]]

推荐阅读