📜  Python – 矩阵中的列到字典转换

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

Python – 矩阵中的列到字典转换

给定一个矩阵,转换为字典,其中第一行中的元素是键,后续行作为值列表。

方法#1:使用列表理解+字典理解

这是可以执行此任务的方式之一。在此,列表推导负责值的构造和映射,字典转换是使用字典推导完成的。

Python3
# Python3 code to demonstrate working of 
# Columns to Dictionary Conversion in Matrix
# Using dictionary comprehension + list comprehension
  
# initializing list
test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
  
# printing original list
print("The original list : " + str(test_list))
  
# dictionary comprehension performing re making of result 
# dictionary
res = {test_list[0][idx]: [test_list[ele][idx]
      for ele in range(1, len(test_list))]
      for idx in range(len(test_list[0]))}
  
# printing result 
print("Reformed dictionary : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Columns to Dictionary Conversion in Matrix
# Using dictionary comprehension + zip()
  
# initializing list
test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
  
# printing original list
print("The original list : " + str(test_list))
  
# appropriate slicing before zip function 
res = {ele[0]: list(ele[1:]) for ele in zip(*test_list)}
  
# printing result 
print("Reformed dictionary : " + str(res))


输出
The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
Reformed dictionary : {4: [10, 19, 9], 5: [8, 4, 3], 7: [3, 6, 6]}

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

这是解决此问题的另一种方法。在此,我们使用 zip() 将所有列元素相互映射,并使用字典理解来执行字典的重新制作。

Python3

# Python3 code to demonstrate working of 
# Columns to Dictionary Conversion in Matrix
# Using dictionary comprehension + zip()
  
# initializing list
test_list = [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
  
# printing original list
print("The original list : " + str(test_list))
  
# appropriate slicing before zip function 
res = {ele[0]: list(ele[1:]) for ele in zip(*test_list)}
  
# printing result 
print("Reformed dictionary : " + str(res))
输出
The original list : [[4, 5, 7], [10, 8, 3], [19, 4, 6], [9, 3, 6]]
Reformed dictionary : {4: [10, 19, 9], 5: [8, 4, 3], 7: [3, 6, 6]}