numpy矩阵的字符串列表

时间:2020-05-05 10:04:52

标签: python numpy

我是初学者。我想将包含字符串的列表转换为numpy矩阵,例如, ['hello','world','this'][[h,e,l,l,o],[w,o,r,l,d],[t,h,i,s]]。我正在寻找n×n numpy矩阵的广义解决方案。

3 个答案:

答案 0 :(得分:0)

您可以这样使用列表推导:

words = ['hello','world','this'] 
letters = [ list(x) for x in words ]

然后创建一个numpy数组:

arr = np.array(letters)

答案 1 :(得分:0)

plz喜欢这个答案

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']]

答案 2 :(得分:0)

如果数组的长度和每个字符串中的字符数都不相同,则无法获得正方形数组。但是,您可以通过使用特殊标记填充较小的字符串来获得m x 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)
[['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']]
相关问题