Chicony - 1 month ago 11

Python Question

I have a list of lists, where each list is associated with a score/weight. I want to produce a new list of lists by randomly selecting from the first one so that those with higher scores will appear more often. The line below works fine when

`population`

`population = [['a','b'],['b','a'],['c','b']]`

list_of_prob = [0.2, 0.2, 0.6]

population = np.random.choice(population, 10, replace=True, p=list_of_prob)

This will give the output

`ValueError: a must be 1-dimensional`

Answer

Instead of passing the actual list, pass a list with indexes into the list.

`np.random.choice`

already allows this, if you pass an int `n`

then it works as if you passed `np.arange(n)`

.

So

```
choice_indices = np.random.choice(len(population), 10, replace=True, p=list_of_prob)
choices = [population[i] for i in choice_indices]
```

Source (Stackoverflow)

Comments