Python – 将矩阵映射到字典


在需要将矩阵映射到字典时,使用简单的迭代。

示例

下面是对同一示例的演示 −

Open Compiler
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("The result is :") print(my_result)

输出

The list :
[[2, 4, 3], [4, 1, 3], [2, 1, 3, 4]]
The result is :
[['Python', 'learn', 'to'], ['learn', 'fun', 'to'], ['Python', 'fun', 'to', 'learn']]

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 定义了一个列表的列表,并在控制台上显示。

  • 定义映射字典的值。

  • 创建一个空列表。

  • 迭代列表,并将映射字典中的元素追加到一个临时变量(空列表)。

  • 否则,追加到空列表中。

  • 这是显示在控制台上的输出。

更新日期: 2021-09-08

838 浏览

开启您的 职业生涯

完成课程,获得认证

开始
广告