如何在Python中生成随机但唯一的数字?

7
我希望生成一个随机数,这个随机数应该是唯一的,也就是说不会被重复生成。我尝试过在每次迭代中将数字添加到列表中,并检查它是否已经存在于列表中。如果已经存在于列表中,则不添加该数字。但我认为这不是一种有效的方法。所以,请帮助我解决这个问题。
    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))

1
你应该生成所有需要的随机数列表,然后对它们进行洗牌。否则,你将需要不断生成随机数,直到得到一个不在列表中的数(对于大量数字来说非常耗时)。 - Jessie
在这个问题的范围内,@GarbageCollector 的值将是唯一的,因为洗牌函数将传递给 OP 所需的值范围,这些值都是唯一的。 - Ajax1234
@Ajax1234 是的,同意。 - Sohaib Farooqi
在您的情况下,您可能只能选择一个随机元素并将其排除在外,或者顺序是否重要? - Elmex80s
这个回答解决了你的问题吗?在范围内生成'n'个唯一的随机数 - Tomerikoo
2个回答

25
通过random.sample,您可以从给定的池中获取指定数量的不重复元素列表:
>>> random.sample(range(500, 510), 9)
[500, 501, 503, 502, 505, 507, 508, 506, 504]

0
import random
low=int(input("ENTER LOWER RANGE:"))
upper=int(input("ENTER UPPER RANGE:"))
l=[low]
count=1
l=[low]
count=1
if (upper-low)>=c or c==upper:
    while count!=c:
        x=random.randint(low,upper)
        if x not in l:
        l.append(x)
        count+=1

for i in range(len(l)):
    print(l[i])

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接