Skip to main content
 首页 » 编程设计

python之如何在 python 中生成随机但唯一的数字

2025年05月04日11mfryf

我想生成一个随机数,这个随机数应该是唯一的,这意味着它不应该重复或再次生成。我尝试制作一个列表,我在每次迭代中追加并检查它是否已经存在于列表中。如果它存在于列表中,则不会附加该编号。但我认为这不是一种有效的方法。所以,请帮助我。

    import random 
    #an empty list to append randomly generated numbers 
    empty = [] 
    while True: 
        #checking from range 500 to 510 
        number = random.randrange(500, 510) 
        if number not in empty: 
            empty.append(number) 
        else: 
            pass 
        #breaking the loop if the length of the numbers is 9 
        if len(empty) == 9: 
            break 
 
    print("Final list --> " + str(empty)) 

请您参考如下方法:

您可以通过 random.sample 从给定的池中获取给定数量的非重复元素的列表。 :

>>> random.sample(range(500, 510), 9) 
[500, 501, 503, 502, 505, 507, 508, 506, 504]