Shuffling a list of objects

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

提交回复
热议问题