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

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

    From the CLI in win xp:

    python -c "import random; print(sorted(set([random.randint(6,49) for i in range(7)]))[:6])"
    

    In Canada we have the 6/49 Lotto. I just wrap the above code in lotto.bat and run C:\home\lotto.bat or just C:\home\lotto.

    Because random.randint often repeats a number, I use set with range(7) and then shorten it to a length of 6.

    Occasionally if a number repeats more than 2 times the resulting list length will be less than 6.

    EDIT: However, random.sample(range(6,49),6) is the correct way to go.

提交回复
热议问题