Shuffling a list of objects

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

    Plan: Write out the shuffle without relying on a library to do the heavy lifting. Example: Go through the list from the beginning starting with element 0; find a new random position for it, say 6, put 0’s value in 6 and 6’s value in 0. Move on to element 1 and repeat this process, and so on through the rest of the list

    import random
    iteration = random.randint(2, 100)
    temp_var = 0
    while iteration > 0:
    
        for i in range(1, len(my_list)): # have to use range with len()
            for j in range(1, len(my_list) - i):
                # Using temp_var as my place holder so I don't lose values
                temp_var = my_list[i]
                my_list[i] = my_list[j]
                my_list[j] = temp_var
    
            iteration -= 1
    

提交回复
热议问题