带有种子的Python随机序列 [英] Python random sequence with seed

查看:115
本文介绍了带有种子的Python随机序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为学校项目这样做(所以我不能使用任何高级功能),而我正在使用Python 2.6.6.

I'm doing this for a school project (so I can't use any advanced features) and I'm using Python 2.6.6.

我有一个从1到1000的数字列表,我的种子将是448.

I have a list of numbers from 1 to 1000 and my seed will be, lets say, 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.

谢谢.

推荐答案

import random
SEED = 448

myList = [ 'list', 'elements', 'go', 'here' ]
random.seed(SEED)
random.shuffle(myList)

print myList

产生

['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

产生

['list', 'elements', 'go', 'here']

多田! originalList现在是myList的原始顺序.

Tada! originalList is now the original ordering of myList.

这篇关于带有种子的Python随机序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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