Python生成无重复随机数问题:现有randint代码输出重复
Hey there! I get it—your current code using random.randint() generates numbers between 0 and 62, but duplicates keep popping up. That makes total sense because each call to randint picks a number independently, with no memory of what was chosen before. Let’s fix that with two straightforward solutions tailored to different needs:
Solution 1: Use random.sample() for a subset of unique numbers
If you need a specific number of unique random values (say, 5 numbers out of the 63 total), random.sample() is perfect. It selects elements from a sequence without replacement, so duplicates are impossible by design.
Here’s the code:
import random # Generate 5 unique random numbers between 0 and 62 (inclusive) unique_numbers = random.sample(range(0, 63), 5) print(unique_numbers)
Note: range(0, 63) covers all integers from 0 to 62 because Python ranges are left-closed, right-open.
Solution 2: Use random.shuffle() for all unique numbers (shuffled order)
If you want to generate every number from 0 to 62 in a random, non-repeating order, create a full list of the range and shuffle it:
import random # Create a list containing all numbers from 0 to 62 number_list = list(range(0, 63)) # Shuffle the list to randomize the order random.shuffle(number_list) print(number_list)
This will give you every number from 0 to 62 exactly once, in a random sequence.
Why your original code had duplicates
random.randint(0,62) generates a single random number each time it’s called. There’s no built-in check for previously generated values, so as you run it more times, the chance of hitting a duplicate goes up. The methods above avoid this by either selecting unique elements upfront or shuffling a complete set of values right away.
内容的提问来源于stack exchange,提问作者Mert Araz

