Better way to shuffle two related lists

后端 未结 7 2230
星月不相逢
星月不相逢 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

    So far, all solutions created new lists in order to solve the problem. If the lists a and b are very long you may want to shuffle them in place. For that you would need a function like:

    import random
    
    def shuffle(a,b):
        assert len(a) == len(b)
        start_state = random.getstate()
        random.shuffle(a)
        random.setstate(start_state)
        random.shuffle(b)
    
    a = [1,2,3,4,5,6,7,8,9]
    b = [11,12,13,14,15,16,17,18,19]
    shuffle(a,b)
    print(a) # [9, 7, 3, 1, 2, 5, 4, 8, 6]
    print(b) # [19, 17, 13, 11, 12, 15, 14, 18, 16]
    

提交回复
热议问题