简体   繁体   English

np.random.choice应该强制吗?

[英]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. 我只是注意到,如果在包含字符串和整数的列表上使用np.random.choice,那么当返回整数时,它们将被强制转换为字符串。 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. 我想我可以做my_list[np.random.choice(range(len(my_list)))] ,但这看起来很丑。

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. NumPy方法可用于NumPy数组,如果给出了Python列表,则它们将在执行其他操作之前将其转换为数组。 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. 一字符的Unicode字符串数组。 The choice is made from this array. 从此数组中进行选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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