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