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

前端 未结 17 2413
灰色年华
灰色年华 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:33

    You can use Numpy library for quick answer as shown below -

    Given code snippet lists down 6 unique numbers between the range of 0 to 5. You can adjust the parameters for your comfort.

    import numpy as np
    import random
    a = np.linspace( 0, 5, 6 )
    random.shuffle(a)
    print(a)
    

    Output

    [ 2.  1.  5.  3.  4.  0.]
    

    It doesn't put any constraints as we see in random.sample as referred here.

    Hope this helps a bit.

提交回复
热议问题