在Python中存储物料清单

2024-06-02 08:09:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python操作一些数据,这些数据只包含部件号及其与其他部件的关系(父/子)。零件在物料清单(BOM)的许多级别上。在Python中存储这些数据的最佳方法是什么?在

最初,为了可读性,我使用了如下所示的嵌套字典和通用零件号(实际零件名是随机字符)。但是,我不认为将数据(部件名)存储为字典键是一个好方法,因为这会使检索部件名变得困难。在

>>> BOM = {}
>>> BOM['Part 1'] = {}
>>> BOM['Part 1']['Part 1.1'] = {}
>>> BOM['Part 1']['Part 1.1']['Part 1.1.1'] = {}
>>> BOM['Part 1']['Part 1.2'] = {}
>>> BOM['Part 1']['Part 1.3'] = {}
>>> BOM['Part 2'] = {}
>>> BOM['Part 2']['Part 2.1'] = {}
>>> BOM['Part 2']['Part 2.2'] = {}
>>> BOM['Part 2']['Part 2.2']['Part 2.2.1'] = {}
>>> print(BOM)

{'Part 1': {'Part 1.1': {'Part 1.1.1': {}}, 'Part 1.2': {}, 'Part 1.3': {}}, 'Part 2': {'Part 2.1': {}, 'Part 2.2': {}, 'Part 2.2.1': {}}}

如果不是嵌套字典,我应该如何存储这些部分?或者我应该以不同的方式使用嵌套字典?在


Tags: 数据方法字典关系部件方式物料bom
3条回答

使用anytree的解决方案

from anytree import Node
bom = {} # dictionary with part as key and list of nodes as value, ex. bom[part] = [Node(part), Node(part), ...]
for (part, parent) in part_list:
    if part not in bom:
        # Create key and initialize value if not in bom
        bom[part] = []
    if parent in bom:
        # Add part to all instances of parent
        for parent_node in bom[parent]:
            bom[part].append(Node(part, parent=parent_node))
    else:
        # If part has no parents, just create the node
        bom[part].append(Node(part))

父/子关系通常存储为树。anytree支持这样的数据结构。这也允许您轻松地检索节点的名称。 如果零件只是像示例中那样递增一的数字,那么一个简单的嵌套列表就足够了(那么嵌套列表的索引和深度意味着零件号的名称)。在

根据我的经验,如果字典中的某个元素没有值,它将作为字典中的列表添加。比如: {'Part 1': {'Part 1.1': ['Part 1.1.1'], 'Part 1.2': {}, 'Part 1.3': {}}, 'Part 2': ['Part 2.1', 'Part 2.2', 'Part 2.2.1']}

相关问题 更多 >