Shuffling a list of objects

后端 未结 23 1980
眼角桃花
眼角桃花 2020-11-22 00:29

I have a list of objects and I want to shuffle them. I thought I could use the random.shuffle method, but this seems to fail when the list is of objects. Is the

23条回答
  •  孤城傲影
    2020-11-22 00:50

    If you have multiple lists, you might want to define the permutation (the way you shuffle the list / rearrange the items in the list) first and then apply it to all lists:

    import random
    
    perm = list(range(len(list_one)))
    random.shuffle(perm)
    list_one = [list_one[index] for index in perm]
    list_two = [list_two[index] for index in perm]
    

    Numpy / Scipy

    If your lists are numpy arrays, it is simpler:

    import numpy as np
    
    perm = np.random.permutation(len(list_one))
    list_one = list_one[perm]
    list_two = list_two[perm]
    

    mpu

    I've created the small utility package mpu which has the consistent_shuffle function:

    import mpu
    
    # Necessary if you want consistent results
    import random
    random.seed(8)
    
    # Define example lists
    list_one = [1,2,3]
    list_two = ['a', 'b', 'c']
    
    # Call the function
    list_one, list_two = mpu.consistent_shuffle(list_one, list_two)
    

    Note that mpu.consistent_shuffle takes an arbitrary number of arguments. So you can also shuffle three or more lists with it.

提交回复
热议问题