pythonrandom

How to use random.choice() to perform multiple random choice?


I want to use random.choice() to choose 5 value from first column in csv as bandwidth. After running the program, the result is 5 identical values. What's wrong with my program?

I have tried random.sample(), but it doesn't work with the Error ' in sample raise ValueError("Sample larger than population or is negative") '. So i just want to use random.choice(), it did not report an error, but extracted 5 duplicate values.

with open('/home/wifi.csv', 'r') as fp:
    reader = csv.reader(fp)
    data = [row for row in reader]
    random.choice(data)

 #choose 5 value from first column as bandwidth
    bw = random.choice(data)[0]*5 
    print(bw)

I expect the output is' 4.5 3.7 2.6 1.8 3.1 ' but the actual output is ' 4.5 4.5 4.5 4.5 4.5 '


Solution

  • Multiplying a list by an integer N duplicates that list N times, which you saw:

    In [4]: [1] * 5
    Out[4]: [1, 1, 1, 1, 1]
    

    What you want to do instead is do the random.choice multiple times. You can do that in a loop, or in something like a list comprehension as below:

    In [5]: x = list(range(10))
    
    In [6]: [random.choice(x) for _ in range(10)]
    Out[6]: [2, 1, 5, 7, 5, 5, 7, 3, 2, 5]