我有一个类列表及其先决条件存储在配对列表中:
classes = [
['Calculus', 'Geometry'],
['Trigonometry', 'Algebra'],
['Geometry', 'Trigonometry']
]
我想将这些类映射到特定的索引,以便为课程构建一个图表,使用如下内容:
course_index = {
0: 'Calculus'
1: 'Geometry'
2: 'Trigonometry'
3: 'Algebra'
}
获取新的整型映射mapped_classes = [[0,1],[2,3],[1,2]]
为了创建course_index
,我创建了一个空索引dict
,并添加了classes
中没有出现在course_index
中的项目
course_index = {key: "" for key in range(4)}
index = 0
for x, y in classes:
if x not in course_index.values():
course_index[index] = x
index += 1
if y not in course_index.values():
course_index[index] = y
index += 1
我不明白的是如何将classes
映射到相应的course_index
来创建mapped_classes
。
是否有一些映射函数可以简化这个过程?我试图解决这个问题如下,我无法改变当前类列表中的值。嵌套循环也非常低效。
for key, val in course_index:
for x, y in classes:
if x = val:
x = key
if y = val:
y = key
翻转course_index字典。枚举类。
invert = {v: k for k, v in course_index.items()}
for i, row in enumerate(classes):
classes[i][0] = invert[classes[i][0]]
classes[i][1] = invert[classes[i][1]]
print(classes)
试试这样写:
mapped_classes = classes.copy()
for key, val in course_index.items():
for e, f in enumerate(classes):
for x in f:
if x == val:
mapped_classes[e][mapped_classes[e].index(x)] = key
print(mapped_classes)