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.
In Python, you can shuffle (= randomize) a list, string, and tuple with random. shuffle() and random. sample() . random.
The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.
You can use range() along with list() to generate a list of integers, and then apply random. shuffle() on that list.
Python Random seed() Method The random number generator needs a number to start with (a seed value), to be able to generate a random number. By default the random number generator uses the current system time. Use the seed() method to customize the start number of the random number generator.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With