How do I create a list of random numbers without duplicates?

前端 未结 17 2261
灰色年华
灰色年华 2020-11-22 13:30

I tried using random.randint(0, 100), but some numbers were the same. Is there a method/module to create a list unique random numbers?

Note: The fol

17条回答
  •  死守一世寂寞
    2020-11-22 13:47

    You can use the shuffle function from the random module like this:

    import random
    
    my_list = list(xrange(1,100)) # list of integers from 1 to 99
                                  # adjust this boundaries to fit your needs
    random.shuffle(my_list)
    print my_list # <- List of unique random numbers
    

    Note here that the shuffle method doesn't return any list as one may expect, it only shuffle the list passed by reference.

提交回复
热议问题