[Python] How to use random.choice() to perform multiple random choice?

Discussão em 'Python' iniciado por Stack, Abril 7, 2025.

  1. Stack

    Stack Membro Participativo

    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 '

    Continue reading...

Compartilhe esta Página