[英]Python:How to assign a list or an array to an array element?
我的代码要求我用某个维度的列表或数组替换维度为3x3的数组的元素。 我该如何实现? 当我编写代码时,它会引发错误,指出:
ValueError: setting an array element with a sequence.
我的代码:
import numpy as np
Y=np.array([1,2,3,4,5,6,7,1,2,3,4,5,6,7,1,2,4])
c_g=np.array([[[1,2],[2,3]],[[4,5],[1,6]]])
xx=[1,2,3]
var=2
theta_g=np.zeros((c_g.shape[0],c_g.shape[1]))
for i in range(c_g.shape[0]):
for j in range(c_g.shape[1]):
theta_g[i][j]=Y[var:var+len(c_g[i][j])**len(xx)]
#here Y is some one dimensional array or list which I want to //
#assign to each element of theta_g
var=var+len(c_g[i][j])**len(xx)
print theta_g
在上面的代码中,我想操作theta_g
。 实际上,我想为theta_g的每个元素分配一个数组。 我该怎么做? 所需的输出: theta_g
,它是尺寸等于c_g
的尺寸的矩阵。
您可以使用np.stack
。
>>> a = [np.array([1, 2]), np.array([3, 4])]
>>> np.stack(a)
array([[1, 2],
[3, 4]])
我认为您应该只将数组元素的类型指定为np.ndarray
或list
,如下所示:
theta_g=np.zeros((c_g.shape[0],c_g.shape[1]), dtype=np.ndarray)
因为您没有真正解释分配的逻辑,所以让我在我自己的示例中进行演示,在该示例中,我将一些数组分配给2x2数组:
from itertools import product
Y = np.array([0,0,1,2,10,20])
Z = np.zeros((2,2), dtype=np.ndarray)
for i,j in product(range(0,2), repeat = 2):
Z[i,j] = Y[2*(i+j):2+2*(i+j)]
print(Z)
版画
[[array([0,0])array([1,2])] [[array([1,2])array([10,20])]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.