Randomly selecting an item from a list of lists gives a ValueError

I have a function that sometimes gives me a list of lists, where nested lists sometimes only have one element, like this one:

a = [['1'], ['3'], ['w']]

And you want to randomly select one item from this main list a. If I try to use np.random.choiceon this list, I get ValueError: a must be 1-dimensional.

But if the list was instead:

b = [['1'], ['3'], ['w', 'w']]

Then use np.random.choiceworks fine. Why is this? And how can I do this so that I can arbitrarily choose from both types of lists?

+4
source share
2 answers

I think it choiceturns your list into an array first.

1- dtype:

In [125]: np.array([['1'], ['3'], ['w', 'w']])
Out[125]: array([['1'], ['3'], ['w', 'w']], dtype=object)
In [126]: _.shape
Out[126]: (3,)

2d :

In [127]: np.array([['1'], ['3'], ['w']])
Out[127]: 
array([['1'],
       ['3'],
       ['w']], 
      dtype='<U1')
In [128]: _.shape
Out[128]: (3, 1)

, . np.array , .

numpy

+3

" ", :

np.random.choice(np.squeeze(a))

, a, b. .

0

Source: https://habr.com/ru/post/1650474/


All Articles