Python - 用字典映射矩阵
给定一个矩阵,用字典值映射它的值。
Input : test_list = [[4, 2, 1], [1, 2, 3]], sub_dict = {1 : “gfg”, 2: “best”, 3 : “CS”, 4 : “Geeks”}
Output : [[‘Geeks’, ‘best’, ‘gfg’], [‘gfg’, ‘best’, ‘CS’]]
Explanation : Matrix elements are substituted using dictionary.
Input : test_list = [[4, 2, 1]], sub_dict = {1 : “gfg”, 2: “best”, 4 : “Geeks”}
Output : [[‘Geeks’, ‘best’, ‘gfg’]]
Explanation : Matrix elements are substituted using dictionary.
方法#1:使用循环
这是执行此任务的蛮力方式。在这里,我们迭代 Matrix 的所有元素并从字典中映射。
Python3
# Python3 code to demonstrate working of
# Mapping Matrix with Dictionary
# Using loop
# initializing list
test_list = [[4, 2, 1], [1, 2, 3], [4, 3, 1]]
# printing original list
print("The original list : " + str(test_list))
# initializing dictionary
sub_dict = {1 : "gfg", 2: "best", 3 : "CS", 4 : "Geeks"}
# Using loop to perform required mapping
res = []
for sub in test_list:
temp = []
for ele in sub:
# mapping values from dictionary
temp.append(sub_dict[ele])
res.append(temp)
# printing result
print("Converted Mapped Matrix : " + str(res))
Python3
# Python3 code to demonstrate working of
# Mapping Matrix with Dictionary
# Using list comprehension
# initializing list
test_list = [[4, 2, 1], [1, 2, 3], [4, 3, 1]]
# printing original list
print("The original list : " + str(test_list))
# initializing dictionary
sub_dict = {1 : "gfg", 2: "best", 3 : "CS", 4 : "Geeks"}
# Using list comprehension to perform required mapping
# in one line
res = [[sub_dict[val] for val in sub] for sub in test_list]
# printing result
print("Converted Mapped Matrix : " + str(res))
输出
The original list : [[4, 2, 1], [1, 2, 3], [4, 3, 1]]
Converted Mapped Matrix : [['Geeks', 'best', 'gfg'], ['gfg', 'best', 'CS'], ['Geeks', 'CS', 'gfg']]
方法#2:使用列表理解
这是可以执行此任务的另一种方式。这只是上述方法的简写。
蟒蛇3
# Python3 code to demonstrate working of
# Mapping Matrix with Dictionary
# Using list comprehension
# initializing list
test_list = [[4, 2, 1], [1, 2, 3], [4, 3, 1]]
# printing original list
print("The original list : " + str(test_list))
# initializing dictionary
sub_dict = {1 : "gfg", 2: "best", 3 : "CS", 4 : "Geeks"}
# Using list comprehension to perform required mapping
# in one line
res = [[sub_dict[val] for val in sub] for sub in test_list]
# printing result
print("Converted Mapped Matrix : " + str(res))
输出
The original list : [[4, 2, 1], [1, 2, 3], [4, 3, 1]]
Converted Mapped Matrix : [['Geeks', 'best', 'gfg'], ['gfg', 'best', 'CS'], ['Geeks', 'CS', 'gfg']]