我有一个由字符串组成的二维numpy数组。有没有一种方法可以将每行中的字符串连接起来,然后使用分隔符字符串(例如换行符)连接生成的字符串?
示例:
pic = np.array([ 'H','e','l','l','o','W','o','r','l','d']).reshape(2,5)
我想要获得:
"Hello\nWorld\n"
在 numpy 之外做这件事并不难:outside
>>> import numpy as np
>>> pic = np.array([ 'H','e','l','l','o','W','o','r','l','d']).reshape(2,5)
>>> pic
array([['H', 'e', 'l', 'l', 'o'],
['W', 'o', 'r', 'l', 'd']],
dtype='|S1')
>>> '\n'.join([''.join(row) for row in pic])
'Hello\nWorld'
此外,还有np.core.defchararray
模块可用于处理字符数组的 "好东西" -- 不过,该模块指出这些仅仅是对Python内置函数和标准库函数的包装器,因此您可能不会获得任何真正的加速优势。
您的想法是正确的。这是一个基于向量化和NumPy的实现,尝试按照这些思路进行 - vectorized NumPythonic
。
# Create a separator string of the same rows as input array
separator_str = np.repeat(['\n'], pic.shape[0])[:,None]
# Concatenate these two and convert to string for final output
out = np.concatenate((pic,separator_str),axis=1).tostring()
np.column_stack
制作一个单行代码 -np.column_stack((pic,np.repeat(['\n'], pic.shape[0])[:,None])).tostring()
示例运行 -
In [123]: pic
Out[123]:
array([['H', 'e', 'l', 'l', 'o'],
['W', 'o', 'r', 'l', 'd']],
dtype='|S1')
In [124]: np.column_stack((pic,np.repeat(['\n'], pic.shape[0])[:,None])).tostring()
Out[124]: 'Hello\nWorld\n'
一种方法是使用str.join()
和list comprehension,例如 -
In [1]: import numpy as np
In [2]: pic = np.array([ 'H','e','l','l','o','W','o','r','l','d']).reshape(2,5)
In [3]: pic
Out[3]:
array([['H', 'e', 'l', 'l', 'o'],
['W', 'o', 'r', 'l', 'd']],
dtype='<U1')
In [4]: '\n'.join([''.join(x) for x in pic])
Out[4]: 'Hello\nWorld'
如果你真的需要在结尾处加上 \n
,你可以在连接字符串后进行拼接。例如 -
In [5]: '\n'.join([''.join(x) for x in pic]) + '\n'
Out[5]: 'Hello\nWorld\n'
\n'
是否重要?通常使用join
将分隔符放置在字符串之间,但不会放在末尾。 - hpaulj