Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
102 views
in Technique[技术] by (71.8m points)

python shuffling with a parameter to get the same result

import random
x = [1, 2, 3, 4, 5, 6]
random.shuffle(x)
print x

I know how to shuffle a list, but is it possible to shuffle it with a parameter such that the shuffling produces the same result every time?

Something like;

random.shuffle(x,parameter)

and the result is the same for this parameter. Say parameter is 4 and the result is [4, 2, 1, 6, 3, 5] every time.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As the documentation explains:

The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don’t share state.

So, you can just create your own random.Random instance, with its own seed, which will not affect the global functions at all:

>>> import random
>>> x = [1, 2, 3, 4, 5, 6]
>>> random.Random(4).shuffle(x)
>>> x
[4, 6, 5, 1, 3, 2]
>>> x = [1, 2, 3, 4, 5, 6]
>>> random.Random(4).shuffle(x)
>>> x
[4, 6, 5, 1, 3, 2]

(You can also keep around the Random instance and re-seed it instead of creating new ones over and over; there's not too much difference.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...