我在 python 中得到了不想要的結果。
目標:我想將常量值分配給 2D 矩陣的各個元素。我有行和列的 indey 串列
idx_container_phi = [22, 19, 25, 23, 22, 21, 22, 30, 16, 12, 14] # row index
idx_container_theta = [22, 19, 10, 23, 22, 7, 22, 8, 16, 19, 11] # column index
thickness = 0.85
sphere_pixels = 36
我做了什么:(1)首先我初始化了具有特定形狀的二維矩陣。
matrix_thickness = np.array([ [0]*sphere_pixels for i in range(sphere_pixels)])
(2) 我初始化了 for 回圈,該回圈一直執行到索引串列的范圍并分配常量值。
for j in range(len(idx_container_phi)):
matrix_thickness[idx_container_phi[j]-1][idx_container_theta[j]-1] = matrix_thickness[idx_container_phi[j]-1][idx_container_theta[j]-1] thickness
但是,在運行代碼時,我得到了每個元素中都包含空值的矩陣。如何將常量值分配給 2D 矩陣中的每個索引位置?
期望輸出:大小為 36 X 36 的矩陣。我想將厚度 (0.85) 的值分配給索引位置[22, 22], [19, 19], [25, 10], [23, 23], [22, 22], [21, 7], [22, 22], [30, 8], [16, 16], [12, 19], [14, 11]。
如果任何索引出現兩次,例如。[22, 22], [22, 22],那么在這種情況下,thickness (0.85)應該添加的值 (0.85 0.85 = 1.70)。
uj5u.com熱心網友回復:
這應該會導致您正在搜索的陣列:
idx_container_phi = [1, 7, 3, 4, 1] # row index
idx_container_theta = [3, 5, 2, 4, 3] # column index
thickness = 0.85
sphere_pixels = 10
matrix_thickness = np.zeros(shape=(sphere_pixels, sphere_pixels))
for row, col in zip(idx_container_phi, idx_container_theta):
matrix_thickness[row, col] = thickness
print(matrix_thickness)
輸出:
[[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]
[0. 0. 0. 1.7 0. 0. 0. 0. 0. 0. ]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]
[0. 0. 0.85 0. 0. 0. 0. 0. 0. 0. ]
[0. 0. 0. 0. 0.85 0. 0. 0. 0. 0. ]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]
[0. 0. 0. 0. 0. 0.85 0. 0. 0. 0. ]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. ]]
uj5u.com熱心網友回復:
所以還有另一種方法可以做到這一點。我知道默認情況下 numpy 陣列默認初始化為dtype = int. 因此,即使在分配常量值(即浮點值)之后,它也會更改為整數值。
提及dtype=float作業并提供所需的輸出。
matrix_thickness = np.array([ [0]*sphere_pixels for i in range(sphere_pixels)], dtype=float)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/530874.html
上一篇:在Python中,如何撰寫一個回圈來從字符#n洗掉到與條件匹配的串列部分中的特定字符(:)?
下一篇:回傳與字串匹配的單詞串列的頻率
