Better way to shuffle two related lists

clwen picture clwen · Aug 1, 2012 · Viewed 30.9k times · Source

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.

Answer

kojiro picture kojiro · Aug 1, 2012

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