我想將元素的索引保存在矩陣中,如下所示
cx = []
for j in range(len(self.correctors_indexes)):
self.lattice[self.correctors_indexes[j]].KickAngle = [self.dkick, 0.00]
lindata0, tune, chrom, lindata = self.lattice.linopt(get_chrom=True, refpts=self.BPM_indexes)
closed_orbitx = lindata['closed_orbit'][:, 0]
cx.append(closed_orbitx)
[row, col] = cx.index(str(closed_orbitx))
file = open("orm_x_CXY_" [row, col] ".txt", "w")
str1 = repr(self.lattice[self.correctors_indexes[j]].KickAngle)
file.write(str1)
file.close()
Cx = np.squeeze(cx) / self.dkick
return Cx
但我收到了錯誤
cannot unpack non-iterable int object
相反,我嘗試添加功能“查找”:
def find(element, matrix):
for i in range(len(matrix)):
for j in range(len(matrix[i])):
if matrix[i][j] == element:
return (i, j)
我使用它如下:
[row, col] = find(closed_orbitx , cx)
file = open("orm_x_CXY_" [row, col] ".txt", "w")
但我得到了錯誤
The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
如何提取矩陣中的元素索引并在檔案名中使用?
uj5u.com熱心網友回復:
您可以使用該函式np.argwhere獲取陣列或矩陣中值的索引,然后將這些值用作檔案名。請參見以下示例:
element = 4
mat = np.array([
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
])
idxs = np.argwhere(mat == element)
print(idxs[0]) # --> [1, 1]
# Unpack the row and column index
row, col = idxs[0]
# You can then use the pair in a filename like
fname = f"file_{row}-{col}.txt"
# or similarly
fname = "file_{}-{}.txt".format(row, col)
但是請注意,它np.argwhere 總是回傳一個索引陣列。
uj5u.com熱心網友回復:
它有效,但是 idxs 的剩余索引呢?這是否意味著元素在矩陣中以不同的索引出現多次?@FabianGD
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/436250.html
