我需要从权重矩阵的值开始创建一个矩阵。在创建和迭代矩阵时,在速度方面保持矩阵的最佳结构是什么?我正在考虑一个列表列表或一个 numpy 2D 数组,但它们对我来说似乎都很慢。我需要的:
numpy array
A = np.zeros((dim, dim))
for r in range(A.shape[0]):
for c in range(A.shape[0]):
if(r==c):
A.itemset(node_degree[r])
else:
A.itemset(arc_weight[r,c])
或者
list of lists
l = []
for r in range(dim):
l.append([])
for c in range(dim):
if(i==j):
l[i].append(node_degree[r])
else:
l[i].append(arc_weight[r,c])
其中 dim 也可以是 20000 , node_degree 是一个向量, arc_weight 是另一个矩阵。我用 C++ 写的,不到 0.5 秒,而其他两个用 python 超过 20 秒。我知道 python 不是 c++,但我需要尽可能快。谢谢你们。