python - 从列表中抽取指定数量的样本。使用所有列表元素
问题描述
我有一个元素列表。现在我想指定我从这个列表中抽取的抽取/样本的数量。但是,我必须确保
(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:]
解决方案
一种方法:
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]]
推荐阅读
- javascript - 如何创建行数据以使用 Apollo graphql 和 Reacr 填充表格?
- angular - 角度材料:SassError:“@include mat”之后的无效 CSS:预期 1 个选择器或规则,是“.core();”
- google-ai-platform - 如何取消部署模型,或者特别是如何从 Vertex AI 上的 shell 获取已部署模型的 id?
- angular - 通过时间线同步来自@swimlane/ngx-charts 的两个折线图
- angular - Bitbucket 管道和 Angular 11 构建错误
- python - 在 PostgresSql 中创建的表在 Python 中不可见
- java - 配置数据源时出错:未指定“url”属性且没有嵌入数据源
- terraform - Terraform:如何在集合的每个元素上运行函数?
- conditional-statements - 如何缩短 XSLT 选择 OR 条件?
- sql - 产品价格突破 SQL