Python – 使用字典映射矩阵
pythonserver side programmingprogramming更新于 2025/10/20 13:32:17
当需要将矩阵映射到字典时,会使用简单的迭代。
示例
下面是相同的演示 −
my_list = [[2, 4, 3], [4, 1, 3], [2, 1, 3, 4]]
print("The list :")
print(my_list)
map_dict = {2 : "Python", 1: "fun", 3 : "to", 4 : "learn"}
my_result = []
for index in my_list:
temp = []
for element in index:
temp.append(map_dict[element])
my_result.append(temp)
print("结果为:")
print(my_result)
输出
The list : [[2, 4, 3], [4, 1, 3], [2, 1, 3, 4]] 结果为: [['Python', 'learn', 'to'], ['learn', 'fun', 'to'], ['Python', 'fun', 'to', 'learn']]
解释
定义列表列表并显示在控制台上。
定义映射字典的值。
创建一个空列表。
迭代列表,并将映射字典中的元素附加到临时变量(空列表)。
否则,将其附加到空列表。
这是显示在控制台上的输出。
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

