Python – 将矩阵转换为字典
给定一个矩阵,将其转换为字典,键为行号,值为嵌套列表。
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))
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]}
方法 #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]}