Shuffling a list of objects

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

提交回复
热议问题