带种子的 Python 随机序列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4557444/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python random sequence with seed
提问by Favolas
I'm doing this for a school project (so I can't use any advanced features) and I'm using Python 2.6.6.
我正在为学校项目执行此操作(因此我无法使用任何高级功能)并且我使用的是 Python 2.6.6。
I have a list of numbers from 1 to 1000 and my seed will be, lets say, 448.
我有一个从 1 到 1000 的数字列表,我的种子将是,比如说,448。
How can I generate a random sequence with that seed so that the numbers in my list will be in a different index?
如何使用该种子生成随机序列,以便列表中的数字位于不同的索引中?
And is it possible, knowing the seed, return the elements in my list to the initial position?
知道种子是否有可能将我列表中的元素返回到初始位置?
Sorry if my question is confusing but English is not my native language.
对不起,如果我的问题令人困惑,但英语不是我的母语。
Thanks.
谢谢。
采纳答案by Hugh Bothwell
import random
SEED = 448
myList = [ 'list', 'elements', 'go', 'here' ]
random.seed(SEED)
random.shuffle(myList)
print myList
results in
结果是
['here', 'go', 'list', 'elements']
Your list is now pseudorandomized.
您的列表现在是伪随机化的。
'Pseudo' is important, because all lists having the same seed and number of items will return in the same 'random' order. We can use this to un-shuffle your list; if it were truly random, this would be impossible.
“伪”很重要,因为所有具有相同种子和项数的列表将以相同的“随机”顺序返回。我们可以用它来取消你的列表;如果真的是随机的,这是不可能的。
Order = list(range(len(myList)))
# Order is a list having the same number of items as myList,
# where each position's value equals its index
random.seed(SEED)
random.shuffle(Order)
# Order is now shuffled in the same order as myList;
# so each position's value equals its original index
originalList = [0]*len(myList) # empty list, but the right length
for index,originalIndex in enumerate(Order):
originalList[originalIndex] = myList[index]
# copy each item back to its original index
print originalList
results in
结果是
['list', 'elements', 'go', 'here']
Tada! originalList is now the original ordering of myList.
多田!originalList 现在是 myList 的原始排序。
回答by Kissaki
A simple check on the python docs http://docs.python.org/library/random.htmltells you about
对 python 文档http://docs.python.org/library/random.html 的简单检查 告诉你
random.seed([x])
which you can use to initialize the seed.
您可以使用它来初始化种子。
To get the items in the order of your initial again, set the seed again and get the random numbers again. You can then use this index to get the content in the list or just use the index for whatever.
要再次按初始顺序获取项目,请再次设置种子并再次获取随机数。然后,您可以使用此索引来获取列表中的内容,或者仅将索引用于任何目的。
You'd just sort the list and it'd be in sorted order again.
您只需对列表进行排序,它就会再次按排序顺序排列。

