Shuffling a list of objects

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

提交回复
热议问题