[英]Properly formatting a string given a python dictionary with keys that are tuples
我有這個python字典。
行數為3
列數為3
matrix = {(0, 1): 2, (0, 2): 3, (1, 0): 4, (1, 2): 6, (2, 0): 7, (2, 1): 8}
關鍵是一個元組(行號,列號),表示矩陣中的位置。
整數形式。
格式化的3x3矩陣:
(0, 2, 3)
(4, 0, 6)
(7, 8, 0)
如果輸入0作為行號參數,如何打印行?*
因此,對於上述字典,如果我將0作為行號的參數傳遞,它將輸出:
(0, 2, 3)
到目前為止,我的代碼:
row = 3
columns = 3
def row(row_number):
matrix = {(0, 1): 2, (0, 2): 3, (1, 0): 4, (1, 2): 6, (2, 0): 7, (2, 1): 8}
values = []
for key, value in matrix.items():
values.append(value)
我以為我可以列出所有鍵,但是字典僅顯示非零值,因此我不確定該怎么做。
[2, 3, 4, 6, 7, 8]
這是一個您可能會發現有用的腳本。 我已經從可用的字典生成了一個完整的矩陣,即填充了0的信息不存在的地方。 然后相應地對其進行索引。
#Generate empty matrix from matrix size ex: 3x3
empty_matrix = [(k, v) for k in range(0,3) for v in range(0,3)]
print("EMPTY MATRIX:", empty_matrix)
matrix = {(0, 1): 2, (0, 2): 3, (1, 0): 4, (1, 2): 6, (2, 0): 7, (2, 1): 8}
final_list = []
#Generate complete matrix i.e fill 0's where info is not available
for element in empty_matrix:
if element in matrix.keys():
value = matrix.get(element)
final_list.append([element, value])
else:
final_list.append([element, 0])
final_matrix = dict(final_list)
print("FINAL MATRIX:" ,final_matrix)
# Indexing the matrix
index = 0 # Get from user, 0 will retrieve 0th row and so on
print("You've retrieved row " + str(index))
for k, v in final_matrix.items():
if index == k[0]:
print(str(v)+',', end='')
輸出:
EMPTY MATRIX: [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
FINAL MATRIX: {(0, 0): 0, (0, 1): 2, (0, 2): 3, (1, 0): 4, (1, 1): 0, (1, 2): 6, (2, 0): 7, (2, 1): 8, (2, 2): 0}
You've retrieved row 0
0,2,3,
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.