小编Bib*_*ari的帖子

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

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

    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))
Run Code Online (Sandbox Code Playgroud)

python random

1
推荐指数
1
解决办法
1261
查看次数

标签 统计

python ×1

random ×1