简体   繁体   中英

Get list of “n” unique random numbers from the given range

I need 3 unique random numbers between 1 to 20.

I have a loop generating 3 random numbers from 1-20. And I don't want there to be any repeats. I have something that works for the first two numbers. But in my code the first and third numbers can still be the same which needs to be fixed.

i = 1

while i <= 3:
    x = random.randint(1, 20)
    print(choice([i for i in range(1, 20) if i != [x]]))
    i += 1

Is there a better way to achieve this in Python?

You can use random.sample() . Below example will return you 3 unique random numbers between 1 to 20.

>>> import random

>>> sample_count = 3   # count of required unique numbers
>>> start_range, end_range = 1, 20  # start and end range

>>> random.sample(range(start_range, end_range+1), sample_count)
[4, 1, 14]

Please refer random.sample() documentation for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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