python 随机种子_带有种子的Python随机序列

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

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.

Thanks.

解决方案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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值