简体   繁体   中英

Is np.random.choice supposed to coerce?

I just noticed that if np.random.choice is used on a list that contains both strings and integers, then when integers are returned, they are coerced to strings. Is this intended behavior?

eg

>>>numpy.random.choice([1,2,3,4]) 1

but

>>>numpy.random.choice(['a',1,2,3,4]) '1'

I guess I can do my_list[np.random.choice(range(len(my_list)))] , but that seems rather ugly.

This is not specific to random choice; NumPy methods work with NumPy arrays, and if given a Python list, they will convert it to an array before doing anything else. The conversion results in:

>>> np.array(['a', 1, 2, 3, 4])
array(['a', '1', '2', '3', '4'],
      dtype='<U1')

an array of one-character Unicode strings. The choice is made from this array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM