Better way to shuffle two related lists Better way to shuffle two related lists python python

Better way to shuffle two related lists


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])


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 shufflelist_1, list_2 = shuffle(list_1, list_2)


If you have to do this often, you could consider adding one level of indirection by shuffling a list of indexes.

Python 2.6.6 (r266:84297, Aug 24 2010, 18:13:38) [MSC v.1500 64 bit (AMD64)] onwin32Type "help", "copyright", "credits" or "license" for more information.>>> import random>>> a = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]>>> b = [2, 4, 6, 8, 10]>>> indexes = range(len(a))>>> indexes[0, 1, 2, 3, 4]>>> random.shuffle(indexes)>>> indexes[4, 1, 2, 0, 3]>>> for index in indexes:...     print a[index], b[index]...[9, 10] 10[3, 4] 4[5, 6] 6[1, 2] 2[7, 8] 8