您要求的不是随机的;事实上,它是相当结构化的。随机数据的关键在于它不是结构化的:你不能说值是什么,只能说它们的平均值。
不过,您仍然可以做您想做的事:只需指定您希望数字落入的范围。
>>> def random_function(*args):
... n = sum(args)
... bottom = 0
... for m in args:
... for _ in range(m):
... yield random.uniform(bottom, bottom + m/n)
... bottom += m/n
...
>>> list(random_function(6,3,1))
[0.1849778317803791, 0.2779140519434712, 0.08380168147928498, 0.5477412922676888
, 0.5158697440011519, 0.5535466918038039, 0.8046993690361345, 0.714614514522802,
0.7102988180048052, 0.9608096335125095]
>>> list(random_function(6,3,1))
[0.29313403848522546, 0.5543469551407342, 0.14208842652528347, 0.344464024804118
7, 0.3168266508239002, 0.5956620829410604, 0.673021479097414, 0.7141779120687652
, 0.7783099010964684, 0.9103924993423906]
解释:
给定(6,3,1)
,算出它们的总和 ( 10
)。我们想要 0 到 6/10 之间的六个数字,6/10 到 6/10 + 3/10 之间的三个数字,以及 6/10 + 3/10 和 6/10 + 3/10 + 1/10 之间的一个数字。我们可以通过调用生成这些
random.uniform(0, 6/10) six times,
random.uniform(6/10, 9/10) three times, and
random.uniform(9/10, 1) once.