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

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

    A very simple function that also solves your problem

    from random import randint
    
    data = []
    
    def unique_rand(inicial, limit, total):
    
            data = []
    
            i = 0
    
            while i < total:
                number = randint(inicial, limit)
                if number not in data:
                    data.append(number)
                    i += 1
    
            return data
    
    
    data = unique_rand(1, 60, 6)
    
    print(data)
    
    
    """
    
    prints something like 
    
    [34, 45, 2, 36, 25, 32]
    
    """
    

提交回复
热议问题