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