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

问题描述 投票:1回答:1

我需要更多有经验的开发人员提供的有关我的数据结构的意见。

我想做什么?

我正在写一个用于映射表的转换器。它可以工作,但是我认为有一种更好的方法来建立结构。

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

映射表:

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]}.")
python data-structures
1个回答
0
投票

您拥有的是三向映射,使用元组列表最简洁地表示它:

# 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 itemgetter

a_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)转换子以进行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]
© www.soinside.com 2019 - 2024. All rights reserved.