+2 votes
in Programming Languages by (15.7k points)
edited by

I am trying to randomly select some values using the following code:

import random as rnd

random_indices_C0 = rnd.sample(pos_of_0, c1_count)

But this code is giving the error: "TypeError: Population must be a sequence or set.  For dicts, use list(d)."

1 Answer

0 votes
by (27.1k points)

If pos_of_0 is a Numpy array or dict, you need to convert it to a list.

As indicated in the error message, you need to convert the variable pos_of_0 to a list to fix the error. Try the following code.

random_indices_C0 = rnd.sample(list(pos_of_0), c1_count)

Here is an example:

>>> import random as rnd

>>> t=np.array([1,1,0,0,1,0,1,0,1,1,0,0,1,1,1])
>>> pos_of_0=np.where(t==1)[0]
>>> pos_of_0
array([ 0,  1,  4,  6,  8,  9, 12, 13, 14])
>>> random_indices_C0 = rnd.sample(list(pos_of_0), c1_count)
>>> random_indices_C0
[0, 6, 4]