Shuffling a list of objects

后端 未结 23 1683
眼角桃花
眼角桃花 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:45

    One can define a function called shuffled (in the same sense of sort vs sorted)

    def shuffled(x):
        import random
        y = x[:]
        random.shuffle(y)
        return y
    
    x = shuffled([1, 2, 3, 4])
    print x
    
    0 讨论(0)
  • 2020-11-22 00:46

    If you happen to be using numpy already (very popular for scientific and financial applications) you can save yourself an import.

    import numpy as np    
    np.random.shuffle(b)
    print(b)
    

    https://numpy.org/doc/stable/reference/random/generated/numpy.random.shuffle.html

    0 讨论(0)
  • 2020-11-22 00:46

    you could build a function that takes a list as a parameter and returns a shuffled version of the list:

    from random import *
    
    def listshuffler(inputlist):
        for i in range(len(inputlist)):
            swap = randint(0,len(inputlist)-1)
            temp = inputlist[swap]
            inputlist[swap] = inputlist[i]
            inputlist[i] = temp
        return inputlist
    
    0 讨论(0)
  • 2020-11-22 00:47

    you can either use shuffle or sample . both of which come from random module.

    import random
    def shuffle(arr1):
        n=len(arr1)
        b=random.sample(arr1,n)
        return b
    

    OR

    import random
    def shuffle(arr1):
        random.shuffle(arr1)
        return arr1
    
    0 讨论(0)
  • 2020-11-22 00:49

    random.shuffle should work. Here's an example, where the objects are lists:

    from random import shuffle
    x = [[i] for i in range(10)]
    shuffle(x)
    
    # print(x)  gives  [[9], [2], [7], [0], [4], [5], [3], [1], [8], [6]]
    # of course your results will vary
    

    Note that shuffle works in place, and returns None.

    0 讨论(0)
  • 2020-11-22 00:49
    """ to shuffle random, set random= True """
    
    def shuffle(x,random=False):
         shuffled = []
         ma = x
         if random == True:
             rando = [ma[i] for i in np.random.randint(0,len(ma),len(ma))]
             return rando
         if random == False:
              for i in range(len(ma)):
              ave = len(ma)//3
              if i < ave:
                 shuffled.append(ma[i+ave])
              else:
                 shuffled.append(ma[i-ave])    
         return shuffled
    
    0 讨论(0)
提交回复
热议问题