我正在嘗試從串列中添加兩個數字,并將兩個數字的相加分配給 Python 中的矩陣。我嘗試如下
import numpy as np
#Create bin and cost list
bin = [10, 20]
cost = [10, 20]
# Create a result matrix of 2 x 2
res_mat = [[0.0 for i in range(len(bin))] for j in range(len(cost))]
for b in bin:
for c in cost:
for i in range(len(bin)):
for j in range(len(cost)):
a = c b
res_mat[i][j] = a
print(np.array(res_mat)) #Print the final result matrix
當我列印時,res_mat我得到如下矩陣:
[[40 40]
[40 40]]
雖然我期待正確的矩陣如下:
[[20 30]
[30 40]]
那么應該做哪些改變才能讓矩陣正確顯示結果呢?
uj5u.com熱心網友回復:
嘗試:
for i, b in enumerate(bin):
for j, c in enumerate(cost):
a = c b
res_mat[i][j] = a
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/334208.html
