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

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

    The solution presented in this answer works, but it could become problematic with memory if the sample size is small, but the population is huge (e.g. random.sample(insanelyLargeNumber, 10)).

    To fix that, I would go with this:

    answer = set()
    sampleSize = 10
    answerSize = 0
    
    while answerSize < sampleSize:
        r = random.randint(0,100)
        if r not in answer:
            answerSize += 1
            answer.add(r)
    
    # answer now contains 10 unique, random integers from 0.. 100
    

提交回复
热议问题