當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python Matrix轉dictionary用法及代碼示例

給定一個矩陣,將其轉換為字典,鍵為行號,值為嵌套列表。

Input:test_list = [[5, 6, 7], [8, 3, 2]]
Output:{1:[5, 6, 7], 2:[8, 3, 2]}
Explanation:Matrix rows are paired with row number in order.

Input:test_list = [[5, 6, 7]]
Output:{1:[5, 6, 7]}
Explanation:Matrix rows are paired with row number in order.

方法#1:使用字典理解+ range()

上述函數的組合可以用來解決這個問題。在此,我們使用字典理解執行迭代任務,並且 range() 可用於執行行編號。

Python3


# Python3 code to demonstrate working of 
# Convert Matrix to dictionary 
# Using dictionary comprehension + range()
  
# initializing list
test_list = [[5, 6, 7], [8, 3, 2], [8, 2, 1]] 
  
# printing original list
print("The original list is:" + str(test_list))
  
# using dictionary comprehension for iteration
res = {idx + 1 :test_list[idx] for idx in range(len(test_list))}
  
# printing result 
print("The constructed dictionary:" + str(res))
輸出
The original list is:[[5, 6, 7], [8, 3, 2], [8, 2, 1]]
The constructed dictionary:{1:[5, 6, 7], 2:[8, 3, 2], 3:[8, 2, 1]}

方法#2:使用字典理解+ enumerate()

上述函數的組合可以用來解決這個問題。在此,字典理解有助於字典的構建,而 enumerate() 有助於迭代,如上述方法中的 range()。

Python3


# Python3 code to demonstrate working of 
# Convert Matrix to dictionary 
# Using dictionary comprehension + enumerate()
  
# initializing list
test_list = [[5, 6, 7], [8, 3, 2], [8, 2, 1]] 
  
# printing original list
print("The original list is:" + str(test_list))
  
# enumerate used to perform assigning row number
res = {idx:val for idx, val in enumerate(test_list, start = 1)}
  
# printing result 
print("The constructed dictionary:" + str(res))
輸出
The original list is:[[5, 6, 7], [8, 3, 2], [8, 2, 1]]
The constructed dictionary:{1:[5, 6, 7], 2:[8, 3, 2], 3:[8, 2, 1]}

相關用法


注:本文由純淨天空篩選整理自manjeet_04大神的英文原創作品 Python – Convert Matrix to dictionary。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。