给定一个矩阵,将其转换为字典,键为行号,值为嵌套列表。
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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。