Better way to shuffle two related lists

后端 未结 7 2208
星月不相逢
星月不相逢 2020-12-13 09:24

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

7条回答
  •  一整个雨季
    2020-12-13 10:14

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

提交回复
热议问题