How do I generate random but unique numbers in python?

梦想与她 提交于 2020-01-11 11:39:10

问题


I want to generate a random number, and that random number should be unique, meaning it should not be repeated or generated again. I have tried making a list where I append in every iteration and check if it is already present in the list or not. If it is present in the list, the number is not appended. But I don't think it is an effective method. So, please help me with it.

    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:


You can get such a list of a given number of non-repeating elements taken from a given pool via random.sample:

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


来源:https://stackoverflow.com/questions/48246528/how-do-i-generate-random-but-unique-numbers-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!