Python中用于映射表的数据结构

我需要更有经验的开发人员为我的数据结构提供一些输入。


我想做什么?


我正在为映射表编写转换器。它有效,但我认为有一种更好的方法来设置结构。


当然,业务逻辑应该易于设置,但同时,结构仍应可读。有人有建议吗?


映射表:


System A    | 4 | 5 |5* |6x | 6x* | 6y | 6y* |  6c | 6c* | 7x | 7x* |  

System B    |   | 4 |5  |6x | 6x* | 6y | 6y* |  6c | 6c* | 7x | 7x* |

System C    |   X0  |X1 |X2 | X3  |    X4    |  X5 |    X6    | X7  |

有三种不同的分级系统(A,B,C)。每个等级都由彼此大致相当的等级组成。


例如。“X4”(系统 C)可以转换为“6y”或“6y”*(系统 A)


例如。“6c”(系统B)可以转换为“X5”(系统C)


当前结构


mapping = {

    "name": ["System A", "System B", "System C"],

    "grade": {

        0: ["4", "", "X0"],

        1: ["5", "4", "X0"],

        2: ["5*", "5", "X1"],

        # ... and so on. 

    }

}


# the current standard is "System A"

input_system = 0


# the input is the index number for the grade

input_grade = 4


# expected output: "In system A it is 6x*."

print(f"In {mapping.name[input_system]} it is {mapping.grade[input_grade][input_system]}.")


江户川乱折腾
浏览 152回答 1
1回答

翻过高山走不出你

您拥有的是一个三向映射,它最简洁地使用元组列表来表示:# Not clear if you want "" or None to represent the non-existent System-B# equivalent of System-A "4"mapping = [    ("4", "", "X0"),    ("5", "4", "X0"),    ("5*", "5", "X1"),    ...]然后,您可以根据元组列表定义 6 个 X->Y 映射中的任何一个。from operator import itemgettera_to_b = dict(map(itemgetter(0, 1), mapping))b_to_a = dict(map(itemgetter(1, 0), mapping))a_to_c = dict(map(itemgetter(0, 2), mapping))c_to_a = dict(map(itemgetter(2, 0), mapping))b_to_c = dict(map(itemgetter(1, 2), mapping))c_to_b = dict(map(itemgetter(2, 1), mapping))您可以通过将 O(1) conversons 换成 O(n) 查找来最小化存储(并不是说我们一开始就使用了很多)。def convert(sys_from, sys_to, grade):    sys_from = {"A": 0, "B": 1, "C": 2}[sys_from]    sys_to = {"A": 0, "B": 1, "C": 2}[sys_to]    for grade in mapping:        if grade[sys_from] == grade:            return grade[sys_from]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python