将矩阵转换为字典列表的Python程序
给定一个矩阵,通过映射相似的索引值将其转换为字典列表。
Input : test_list = [[“Gfg”, [1, 2, 3]], [“best”, [9, 10, 11]]]
Output : [{‘Gfg’: 1, ‘best’: 9}, {‘Gfg’: 2, ‘best’: 10}, {‘Gfg’: 3, ‘best’: 11}]
Input : test_list = [[“Gfg”, [1, 2, 3]]]
Output : [{‘Gfg’: 1}, {‘Gfg’: 2}, {‘Gfg’: 3}]
执行此任务的粗暴方式是使用循环。在此,我们迭代 Matrix 中的所有元素,并将字典绑定键更新为字典中的适当值。
Python3
# initializing list
test_list = [["Gfg", [1, 2, 3]],
["is", [6, 5, 4]], ["best", [9, 10, 11]]]
# printing original list
print("The original list : " + str(test_list))
# using loop to bind Matrix elements to dictionary
res = []
for key, val in test_list:
for idx, val in enumerate(val):
# append values according to rows structure
if len(res) - 1 < idx:
res.append({key: val})
else:
res[idx].update({key: val})
# printing result
print("Converted dictionary : " + str(res))
输出:
The original list : [[‘Gfg’, [1, 2, 3]], [‘is’, [6, 5, 4]], [‘best’, [9, 10, 11]]]
Converted dictionary : [{‘Gfg’: 1, ‘is’: 6, ‘best’: 9}, {‘Gfg’: 2, ‘is’: 5, ‘best’: 10}, {‘Gfg’: 3, ‘is’: 4, ‘best’: 11}]