Python numpy矩阵的字符串列表

Python numpy矩阵的字符串列表,python,numpy,Python,Numpy,我是初学者。我想把一个带字符串的列表转换成一个numpy矩阵,例如, [hello',[world',[this']到[h,e,l,l,o],[w,o,r,l,d],[t,h,i,s]。我正在寻找n×n numpy矩阵的广义解。您可以使用列表理解,如下所示: words=['hello'、'world'、'this'] 字母=[listx代表x的文字] 然后创建一个numpy数组: arr=np.arrayletters 我喜欢这个答案 arr = ['hello', 'world', 'thi

我是初学者。我想把一个带字符串的列表转换成一个numpy矩阵,例如,
[hello',[world',[this']到[h,e,l,l,o],[w,o,r,l,d],[t,h,i,s]。我正在寻找n×n numpy矩阵的广义解。

您可以使用列表理解,如下所示:

words=['hello'、'world'、'this'] 字母=[listx代表x的文字] 然后创建一个numpy数组:

arr=np.arrayletters 我喜欢这个答案

arr = ['hello', 'world', 'this']
arr = [list(i) for i in arr]

print(arr)

输出:['h','e','l','l','o'],['w','o','r','l','d'],['t','h','i','s'].

如果数组的长度和每个字符串中的字符数不相同,则无法获得方形数组。但是,您可以通过使用特殊标记填充较小的字符串来获得m×n numpy数组

import numpy as np


a_main = ['hello', 'world', 'this']

a = [list(a_i) for a_i in a_main]
print(a)
cols = 5
oov_token = 'Z'

for i in range(len(a)):
  if len(a[i]) < cols:
    a[i] = list( ''.join(k for k in a[i]).rjust(cols, oov_token))

print(a)

a = np.array(a, dtype = np.chararray)
print(a.shape)
print(a)

这不是一个numpy数组输出,尽管您需要展示您已经尝试过的内容,到目前为止您已经编写了哪些代码?请不要自己不费吹灰之力就试图寻求帮助。
[['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd'], ['t', 'h', 'i', 's']]
[['h', 'e', 'l', 'l', 'o'], ['w', 'o', 'r', 'l', 'd'], ['Z', 't', 'h', 'i', 's']]
(3, 5)
[['h' 'e' 'l' 'l' 'o']
 ['w' 'o' 'r' 'l' 'd']
 ['Z' 't' 'h' 'i' 's']]