如何创建一个任意长度字符串的numpy数组? [英] How to create a numpy array of arbitrary length strings?

查看:265
本文介绍了如何创建一个任意长度字符串的numpy数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Python的新手,但是看起来给定的字符串可以(有效)为任意长度.即您可以使用string str并继续添加:str += "some stuff...".有没有办法制作这样的字符串数组?

I'm a complete rookie to Python, but it seems like a given string is able to be (effectively) arbitrary length. i.e. you can take a string str and keeping adding to it: str += "some stuff...". Is there a way to make an array of such strings?

当我尝试此操作时,每个元素仅存储一个字符

When I try this, each element only stores a single character

strArr = numpy.empty(10, dtype='string')
for i in range(0,10)
    strArr[i] = "test"

另一方面,我知道我可以初始化一定长度字符串的数组,即

On the other hand, I know I can initialize an array of certain length strings, i.e.

strArr = numpy.empty(10, dtype='s256')

最多可以存储10个字符串,最多256个字符.

which can store 10 strings of up to 256 characters.

推荐答案

您可以通过创建dtype=object数组来实现.如果您尝试将长字符串分配给普通的numpy数组,则会将其截断:

You can do so by creating an array of dtype=object. If you try to assign a long string to a normal numpy array, it truncates the string:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'], 
      dtype='|S6')

但是当您使用dtype=object时,会得到一个python对象引用数组.因此,您可以拥有python字符串的所有行为:

But when you use dtype=object, you get an array of python object references. So you can have all the behaviors of python strings:

>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)

实际上,因为它是对象数组,所以您可以将任何种python对象分配给该数组:

Indeed, because it's an array of objects, you can assign any kind of python object to the array:

>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)

但是,这取消了使用numpy的许多好处,它是如此之快,因为它适用于大型连续的原始内存块.使用python对象会增加很多开销.一个简单的例子:

However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:

>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop

这篇关于如何创建一个任意长度字符串的numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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