python seed()不保持相同的顺序 [英] python seed() not keeping same sequence

查看:186
本文介绍了python seed()不保持相同的顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用random.seed()尝试使random.sample()保持相同,因为我从列表中采样了更多的值,并且在某些时候数字发生了变化..... seed()函数的目的是保持数字相同.

I'm using a random.seed() to try and keep the random.sample() the same as I sample more values from a list and at some point the numbers change.....where I thought the one purpose of the seed() function was to keep the numbers the same.

这里做了一个测试,证明它没有保持相同的数字.

Heres a test I did to prove it doesn't keep the same numbers.

import random

a=range(0,100)
random.seed(1)
a = random.sample(a,10)
print a

然后将样本更改得更高,顺序也会发生变化(至少对我而言,他们总是这样做):

then change the sample much higher and the sequence will change(at least for me they always do):

a = random.sample(a,40)
print a

我有点像个新手,所以也许这是一个简单的解决方法,但是对此我将提供任何帮助. 谢谢!

I'm sort of a newb so maybe this is an easy fix but I would appreciate any help on this. Thanks!

推荐答案

如果要从生成器中提取独立的样本,将会发生的事情恰好是您所期望的:

If you were to draw independent samples from the generator, what would happen would be exactly what you're expecting:

In [1]: import random

In [2]: random.seed(1)

In [3]: [random.randint(0, 99) for _ in range(10)]
Out[3]: [13, 84, 76, 25, 49, 44, 65, 78, 9, 2]

In [4]: random.seed(1)

In [5]: [random.randint(0, 99) for _ in range(40)]
Out[5]: [13, 84, 76, 25, 49, 44, 65, 78, 9, 2, 83, 43 ...]

如您所见,前十个数字确实是相同的.

As you can see, the first ten numbers are indeed the same.

random.sample()正在抽取样本而没有替换的事实正在困扰您.要了解这些算法的工作原理,请参见水库采样.从本质上讲,发生的事情是稍后样本可以将更早样本从结果集中推出.

It is the fact that random.sample() is drawing samples without replacement that's getting in the way. To understand how these algorithms work, see Reservoir Sampling. In essence what happens is that later samples can push earlier samples out of the result set.

一种替代方法是将索引列表随机排列,然后采用10或40个第一元素:

One alternative might be to shuffle a list of indices and then take either 10 or 40 first elements:

In [1]: import random

In [2]: a = range(0,100)

In [3]: random.shuffle(a)

In [4]: a[:10]
Out[4]: [48, 27, 28, 4, 67, 76, 98, 68, 35, 80]

In [5]: a[:40]
Out[5]: [48, 27, 28, 4, 67, 76, 98, 68, 35, 80, ...]

这篇关于python seed()不保持相同的顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆