<type 'numpy.string_'> 类型之间有什么区别?和&lt;输入'str'&gt;? [英] What is the difference between the types &lt;type &#39;numpy.string_&#39;&gt; and &lt;type &#39;str&#39;&gt;?

查看:35
本文介绍了<type 'numpy.string_'> 类型之间有什么区别?和&lt;输入'str'&gt;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

类型 之间有区别吗?

解决方案

numpy.string_ 是用于包含固定宽度字节字符串的数组的 NumPy 数据类型.另一方面,str 是原生 Python 类型,不能用作 NumPy 数组的数据类型*.

如果您创建一个包含字符串的 NumPy 数组,该数组将使用 numpy.string_ 类型(或 Python 3 中的 numpy.unicode_ 类型).更准确地说,数组将使用 np.string_ 的子数据类型:

<预><代码>>>>a = np.array(['abc', 'xy'])>>>一个数组(['abc', 'xy'], dtype='<S3')>>>np.issubdtype('<S3', np.string_)真的

在这种情况下,数据类型是 '<S3':< 表示字节顺序(小端),S 表示字符串类型,3 表示数组中的每个值最多包含三个字符(或字节).

np.string_str 共享的一个属性是不变性.尝试增加 Python str 对象的长度将在内存中创建一个新对象.同样,如果您希望固定宽度的 NumPy 数组容纳更多字符,则必须在内存中创建一个新的更大的数组.

<小时>

* 请注意,可以创建一个 NumPy object 数组,其中包含对 Python str 对象的references,但此类数组的行为完全不同到普通数组.

Is there a difference between the types <type 'numpy.string_'> and <type 'str'>?

解决方案

numpy.string_ is the NumPy datatype used for arrays containing fixed-width byte strings. On the other hand, str is a native Python type and can not be used as a datatype for NumPy arrays*.

If you create a NumPy array containing strings, the array will use the numpy.string_ type (or the numpy.unicode_ type in Python 3). More precisely, the array will use a sub-datatype of np.string_:

>>> a = np.array(['abc', 'xy'])
>>> a
array(['abc', 'xy'], dtype='<S3')
>>> np.issubdtype('<S3', np.string_)
True

In this case the datatype is '<S3': the < denotes the byte-order (little-endian), S denotes the string type and 3 indicates that each value in the array holds up to three characters (or bytes).

One property that np.string_ and str share is immutability. Trying to increase the length of a Python str object will create a new object in memory. Similarly, if you want fixed-width NumPy array to hold more characters, a new larger array will have to be created in memory.


* Note that it is possible to create a NumPy object array which contains references to Python str objects, but such arrays behave quite differently to normal arrays.

这篇关于<type 'numpy.string_'> 类型之间有什么区别?和&lt;输入'str'&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆