Say I have two simple lists,
a = ['Spears', "Adele", "NDubz", "Nicole", "Cristina"] b = [1,2,3,4,5] len(a) == len(b)
What I would like to do is randomize a
and b
but maintain the order. So, something like:
a = ["Adele", 'Spears', "Nicole", "Cristina", "NDubz"] b = [2,1,4,5,3]
I am aware that I can shuffle one list using:
import random random.shuffle(a)
But this just randomizes a
, whereas, I would like to randomize a
, and maintain the "randomized order" in list b
.
Would appreciate any guidance on how this can be achieved.
Method : Using zip() + shuffle() + * operator In this method, this task is performed in three steps. Firstly, the lists are zipped together using zip(). Next step is to perform shuffle using inbuilt shuffle() and last step is to unzip the lists to separate lists using * operator.
Python Random shuffle() Method 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.
Use sorted(). It returns a new list and if you use a random number as key, it will be scrambled.
To use this with shuffle, type r = random. SystemRandom() to generate the random number generator and then call r. shuffle(x) on your list x. Other functions, including choice and sample, can also be used with the SystemRandom generator.
I'd combine the two lists together, shuffle that resulting list, then split them. This makes use of zip()
a = ["Spears", "Adele", "NDubz", "Nicole", "Cristina"] b = [1, 2, 3, 4, 5] combined = list(zip(a, b)) random.shuffle(combined) a[:], b[:] = zip(*combined)
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