字符串到单个字符的数组,而不必沿途转换为列表

2024-04-20 13:46:30 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有一种方法可以将Python字符串转换为NumPy字符数组,其中每个字符都是自己的数组元素,而不必首先将字符串转换为列表?我有一个程序,必须用大量的数据来实现这一点,我已经确定转换步骤本身是一个瓶颈,但我似乎找不到任何NumPy函数可以直接获取字符串并以这种方式转换它,而不首先创建一个泛型Python列表。你知道吗


Tags: 数据方法函数字符串程序numpy元素列表
2条回答

IIUC,可以使用^{}指定数据类型为长度unicode1。你知道吗

>>> np.fromiter('abcdefg', (np.unicode,1))

official docs

The chararray class exists for backwards compatibility with Numarray, it is not recommended for new development. Starting from numpy 1.4, if one needs arrays of strings, it is recommended to use arrays of dtype object_, string_ or unicode_, and use the free functions in the numpy.char module for fast vectorized string operations.

因此,如果您需要使用isalpha()这样的方法,请使用np.char模块,如下所示,而不再使用np.chararray类:

>>> np.char.isalpha(x)
import numpy as np
for i in np.fromstring('ab', dtype='|S1', sep=''):
    print(i.isalpha())

或者

np.fromiter('abcdefg', (np.str,1))

相关问题 更多 >