Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

randomizing two lists and maintaining order in python

Tags:

python

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.

like image 315
JohnJ Avatar asked Nov 12 '12 12:11

JohnJ


People also ask

How do you randomize two lists in Python?

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.

How do you randomize the order of items in a list in Python?

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.

How do you scramble a list in Python?

Use sorted(). It returns a new list and if you use a random number as key, it will be scrambled.

How do you randomize data in Python?

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.


1 Answers

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) 
like image 131
Tim Avatar answered Sep 20 '22 08:09

Tim