Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to shuffle two related lists

Is there better ways to randomly shuffle two related lists without breaking their correspondence in the other list? I've found related questions in numpy.array and c# but not exactly the same one.

As a first try, a simple zip trick will do:

import random a = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] b = [2, 4, 6, 8, 10] c = zip(a, b) random.shuffle(c) a = [e[0] for e in c] b = [e[1] for e in c] print a print b 

It will get the output:

[[1, 2], [7, 8], [3, 4], [5, 6], [9, 10]] [2, 8, 4, 6, 10] 

Just find it a bit awkward. And it also need an additional list as well.

like image 988
clwen Avatar asked Aug 01 '12 18:08

clwen


People also ask

How do you shuffle two lists?

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 I shuffle two arrays simultaneously?

To shuffle both arrays simultaneously, use numpy. random. shuffle(c) . In production code, you would of course try to avoid creating the original a and b at all and right away create c , a2 and b2 .

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

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 randomize multiple lists in Python?

The syntax is: random. sample(list,k) where k represents, number of values to be sampled. You can check data science with python course to go through the topic of data science with python.


2 Answers

Given the relationship demonstrated in the question, I'm going to assume the lists are the same length and that list1[i] corresponds to list2[i] for any index i. With that assumption in place, shuffling the lists is as simple as shuffling the indices:

 from random import shuffle  # Given list1 and list2   list1_shuf = []  list2_shuf = []  index_shuf = list(range(len(list1)))  shuffle(index_shuf)  for i in index_shuf:      list1_shuf.append(list1[i])      list2_shuf.append(list2[i]) 
like image 136
kojiro Avatar answered Oct 05 '22 17:10

kojiro


If you are willing to install a few more packages:

Req: NumPy (>= 1.6.1), SciPy (>= 0.9).

pip install -U scikit-learn

from sklearn.utils import shuffle list_1, list_2 = shuffle(list_1, list_2) 
like image 31
Tihomir Nedev Avatar answered Oct 05 '22 18:10

Tihomir Nedev