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.
Given the relationship demonstrated in the question, I’m going to assume the lists are the same length and that
list1[i]corresponds tolist2[i]for any indexi. With that assumption in place, shuffling the lists is as simple as shuffling the indices: