0

I have two lists, each of length 100. The first list contains indices (call this list i) and the second contains the probability that each of those indices will be selected (call this list P). I would like to choose one index using the given probabilities.

I have tried to use the following code:

index = random.choice(i, P)

to select one index from the list. However, I get the error:

ValueError: sequence too large; cannot be greater than 32

Is there a way to get around this error and select an element from a larger (100 element) list with weighted probabilities? Perhaps there is another function besides numpy.random() that I can use? Or maybe a way to look at only 32 elements of the list at one time (although I'm concerned about altering the given probability distribution)? Thank you in advance for your help!

sshashank124
  • 31,495
  • 9
  • 67
  • 76
Mjdavis
  • 1
  • 1
  • 2

1 Answers1

0

random.choice() only takes one argument: the sequence to choose from.

You need the random.choices() function, which takes weights as the second (first named) argument.

See the manual.

Example usage:

import random

nums = [random.randint(0, 99) for _ in range(100)]
weights = [float(random.randint(0, 99)) for _ in range(100)]
weights = [w/sum(weights) for w in weights]  # normalize to 1. not nessecary for random.choice

print(random.choices(nums, weights))

Try it online!

agtoever
  • 1,669
  • 16
  • 22
  • Thank you, this worked for me! I don't know if importing random rather than numpy.random had an effect, but I certainly needed to be using choices() not choice(). – Mjdavis Dec 28 '19 at 03:28