Yao Chen Yao Chen - 1 year ago 68
Python Question

How do I create a LIST of unique random numbers?

I tried using

random.randint(0, 100)
, but some numbers were the same. Is there a method/module to create a list unique random numbers?

def getScores():
# open files to read and write
f1 = open("page.txt", "r");
p1 = open("pgRes.txt", "a");

gScores = [];
bScores = [];
yScores = [];

# run 50 tests of 40 random queries to implement "bootstrapping" method
for i in range(50):
# get 40 random queries from the 50
lines = random.sample(f1.readlines(), 40);

Answer Source

This will return a list of 10 numbers selected from the range 0 to 99, without duplicates.

random.sample(range(100), 10)

With reference to your specific code example, you probably want to read all the lines from the file once and then select random lines from the saved list in memory. For example:

all_lines = f1.readlines()
for i in range(50):
    lines = random.sample(all_lines, 40)

This way, you only need to actually read from the file once, before your loop. It's much more efficient to do this than to seek back to the start of the file and call f1.readlines() again for each loop iteration.