样本大于种群Python

2024-10-01 11:38:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个包含基数nlittle的整数的列表,这些整数必须是随机的(valuemin,value),但是我在运行下面的代码时得到了大于population的错误样本

    nlittle=random.randrange(5,15)
    value=random.randint(1,100)
    valuemin=int(valore*0.8)
    minmoduniform=5*valoremin
    maxmoduniform=20*valore
    puniform=random.sample(xrange(valuemin,value), nlittle)
    rouniform=random.sample(xrange(valuemin,value), nlittle)

如果nlittle(在我的代码中)大于xrange的差异,我如何解决这个问题并打印一个列表? 泰


Tags: sample代码列表value错误整数random样本
2条回答

//获取基数

我同意@Jasper。重新措辞你的问题。在

一个可能的解决方案是使用

n= xrange(valuemin,value)
m= xrange(valuemin,value)
puniform=random.sample(n, min(len (n) ,nlittle))
rouniform=random.sample(m, min(len(m) ,nlittle))

//查看代码可能出错的原因。在

您的代码片段可能在多个实例中遇到问题。在

我们来接个案子吧。在

nlittle是一个介于5和15之间的随机整数。说是15岁 值介于0到100之间。假设它被分配了3。 希望,瓦莱敏不到三个说1。(我不能确定,因为我不知道瓦洛雷明)

您试图从一个包含2个对象的列表中获取15个对象的示例,该列表给了您错误。在

请参阅随机库的文档。那会更有帮助 https://docs.python.org/2/library/random.html

我正在添加一个摘录从网站为随机抽样(pop,k)在下面。在

random.sample(population, k)

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

New in version 2.3.

Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).

Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.

To choose a sample from a range of integers, use an xrange() object as an argument. This is especially fast and space efficient for sampling from a large population: sample(xrange(10000000), 60).

rands = [random.randint(valuemin, value) for x in xrange(nlittle)]

这将在valuemin和{}之间选取nlittle整数。在

相关问题 更多 >