简体   繁体   English

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

[英]How do I generate random but unique numbers in python?

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.我尝试在每次迭代中列出我 append 的列表,并检查它是否已经存在于列表中。 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))

You can get such a list of a given number of non-repeating elements taken from a given pool via random.sample : 您可以通过random.sample从给定的池中获取给定数量的非重复元素的random.sample

>>> random.sample(range(500, 510), 9)
[500, 501, 503, 502, 505, 507, 508, 506, 504]
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])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM