Better way to shuffle two related lists

Viewed 36215

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.

8 Answers

You can do an unzip at the end to limit the awkwardness a bit?

import numpy as np
list1 = [1,2,3]
list2 = [4,5,7]
list_zipped = list(zip(list1,list2))
np.random.shuffle(list_zipped)
list1,list2 = zip(*z) #unzipping

Modified version of AlexConfused's approach which is more general and be copied and used directly:

from random import shuffle, getstate, setstate


def shuffle_inplace(lst, state):
    """ shuffle multiple lists in-place using order determined by state """
    setstate(state)
    shuffle(lst)


lst1 = [0, 1, 2, 3, 4]
lst2 = [5, 6, 7, 8, 9]

s = getstate()
shuffle_inplace(lst1, s)
shuffle_inplace(lst2, s)

print(lst1)
print(lst2)
Related