[英]Structure for storing string values in two-dimensional list in Python
我需要創建一個類似矩陣的結構,該結構可以通過其列和行的名稱進行訪問。
'''
Misalign CPU Ret
LU_factor 0 6 21
Random 2 10 5
'''
row=["LU_factor","Random"]
col=['Misalign', 'CPU', 'Ret']
Total=[['0', '6', '21'],['2', '10', '5']]
for i in range(0,len(Total)):
for j in range(0,len(Total[i])):
print(Total[i][j],end=" ")
# Matrix[row[i]][col[j]] =Total[i][j]
#print(Matrix)
我不知道應該使用哪種格式或數據結構來存儲上述數據,以便能夠像這樣訪問:
Matrix["LU_factor"]["CPU"] =6
Matrix["Random"]["Ret"] = 5
我已經找到了一種通過numpy structured array
解決方案,但是我正在尋找不使用numpy的解決方案。 提前致謝。
您可以使用字典的字典,例如:
M = {"LU_factor": {'Misalign': 0, 'CPU': 6, 'Ret': 21}, 'Random': {'Misalign': 2, 'CPU': 10, 'Ret': 5}}
應該可以使用M["LU_factor"]["CPU"]
和M["LU_factor"]["CPU"] = 5
分別訪問或分配值。
具體來說,您可以使用示例來通過dict理解來構建所需的結構:
row=["LU_factor","Random"]
col=['Misalign', 'CPU', 'Ret']
Total=[['0', '6', '21'],['2', '10', '5']]
M = {r:{c:Total[k][i] for i, c in enumerate(col)} for k, r in enumerate(row)}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.