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.
Method : Using zip() + shuffle() + * operator In this method, this task is performed in three steps. Firstly, the lists are zipped together using zip(). Next step is to perform shuffle using inbuilt shuffle() and last step is to unzip the lists to separate lists using * operator.
To shuffle both arrays simultaneously, use numpy. random. shuffle(c) . In production code, you would of course try to avoid creating the original a and b at all and right away create c , a2 and b2 .
Python Random shuffle() Method The shuffle() method takes a sequence, like a list, and reorganize the order of the items. Note: This method changes the original list, it does not return a new list.
The syntax is: random. sample(list,k) where k represents, number of values to be sampled. You can check data science with python course to go through the topic of data science with python.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With