Skip to main content
 首页 » 编程设计

Python之将列表中的字符串元素添加到数组中

2024年11月01日24java哥

这是我想做的一个例子。我想获取 b 并将其添加到我的数组中,但采用特定格式(同样,我只想知道执行此操作的步骤,我的代码处理字符串):

import numpy as np 
 
a = np.zeros(25, dtype= np.character).reshape(5,5) 
b = [1,2,3,4,5,6,7,8,9] 
 
for i in b: 
 
    a[1:4,1:4] = i 
 
print a 

输出:

[['' '' '' '' ''] 
 ['' '9' '9' '9' ''] 
 ['' '9' '9' '9' ''] 
 ['' '9' '9' '9' ''] 
 ['' '' '' '' '']] 

但我想要的是:

[['' '' '' '' ''] 
 ['' '1' '2' '3' ''] 
 ['' '4' '5' '6' ''] 
 ['' '7' '8' '9' ''] 
 ['' '' '' '' '']] 

谁能告诉我如何做到这一点?谢谢。

请您参考如下方法:

import numpy as np 
 
a = np.zeros(25, dtype= np.character).reshape(5,5) 
b = np.array([1,2,3,4,5,6,7,8,9]) 
a[1:4,1:4] = b.reshape(3,3) 
print(a) 

产量

[['' '' '' '' ''] 
 ['' '1' '2' '3' ''] 
 ['' '4' '5' '6' ''] 
 ['' '7' '8' '9' ''] 
 ['' '' '' '' '']]