📜  将矩阵转换为字典值列表的Python程序

📅  最后修改于: 2022-05-13 01:55:36.533000             🧑  作者: Mango

将矩阵转换为字典值列表的Python程序

给定 Matrix,任务是编写一个Python程序,将每一列的值映射为另一个列表中的自定义键。

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

在这种情况下,使用 zip() 完成列与自定义列表索引元素的映射,完成字典理解以将提取的键分配给映射值。

Python3
# Python3 code to demonstrate working of
# Convert Matrix to Dictionary Value List
# Using dictionary comprehension + zip()
from collections import defaultdict
  
# initializing list
test_list = [[4, 5, 6], [1, 3, 5], [3, 8, 1], [10, 3, 5]]
               
# printing original list
print("The original list is : " + str(test_list))
  
# initializing map list 
map_list = [4, 5, 6]
  
# mapping column using zip(), dictionary comprehension for key
# converts to list of dictionary
temp = [{key : val for key, 
         val in zip(map_list, idx)} for idx in test_list]
  
# convert to dictionary value list 
res = defaultdict(list) 
{res[key].append(sub[key]) for sub in temp for key in sub}
  
# printing result
print("Converted Dictionary : " + str(dict(res)))


Python3
# Python3 code to demonstrate working of
# Convert Matrix to Dictionary Value List
# Using dict() + list comprehension + zip()
from collections import defaultdict
  
# initializing list
test_list = [[4, 5, 6], [1, 3, 5], [3, 8, 1], [10, 3, 5]]
               
# printing original list
print("The original list is : " + str(test_list))
  
# initializing map list 
map_list = [4, 5, 6]
  
# mapping column using zip() and conversion using using dict()
# converts to list of dictionary
temp = [dict(zip(map_list, sub)) for sub in test_list]
  
# convert to dictionary value list 
res = defaultdict(list) 
{res[key].append(sub[key]) for sub in temp for key in sub}
  
# printing result
print("Converted Dictionary : " + str(dict(res)))


输出:

方法 2:使用dict() +列表推导+ zip()

在这种情况下,将值映射到字典键和转换的任务是使用 dict() 和 zip() 以及字典理解完成的。休息功能类似于上述方法。

蟒蛇3

# Python3 code to demonstrate working of
# Convert Matrix to Dictionary Value List
# Using dict() + list comprehension + zip()
from collections import defaultdict
  
# initializing list
test_list = [[4, 5, 6], [1, 3, 5], [3, 8, 1], [10, 3, 5]]
               
# printing original list
print("The original list is : " + str(test_list))
  
# initializing map list 
map_list = [4, 5, 6]
  
# mapping column using zip() and conversion using using dict()
# converts to list of dictionary
temp = [dict(zip(map_list, sub)) for sub in test_list]
  
# convert to dictionary value list 
res = defaultdict(list) 
{res[key].append(sub[key]) for sub in temp for key in sub}
  
# printing result
print("Converted Dictionary : " + str(dict(res)))

输出: