在给定的帐户列表中查找层次结构的Pythonic方法

2024-09-30 18:27:53 发布

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

我有一个MySQL列,包含以下信息:

codes = [
    "[1]",
    "[1-1]",
    "[1-1-01]",
    "[1-1-01-01]",
    "[1-1-01-02]",
    "[1-1-01-03]",
    "[1-1-02]",
    "[1-1-02-01]",
    "[1-1-02-02]"
    "[1-2]",
    "[1-2-01]",
    "[1-2-01-01]",
    "[2]",
    "[2-1]",
    "[2-1-01-01]",
    "[2-1-01-02]"
]

这是帐户的层次结构,我需要知道,对于每个帐户,哪个是父级,哪个是要添加到名为AccountsTree的辅助表中的子级。你知道吗

我的模型是:

Accounts:
    id = db.Column(Integer)
    account = db.Column(Integer)
    ...
    numbers = db.Column(Integer)

AccountsTree:
    id = db.Column(Integer)
    parent = db.Column(Integer, db.ForeignKey('Accounts.id')
    child = db.Column(Integer, db.ForeignKey('Accounts.id')

我开始编写这样的代码:

For each_element in code_list:
    replace "[" and "]"
    split strings in '-' and
    make a new list of lists: each list element is a list of codes, each element of the inner list is a level

但这看起来不太好,而且我似乎在增加不必要的复杂性。你知道吗

我的工作流程是:

(1) Import XLS from front end
(2) Parse XLS and add information to Accounts table
(3) Find out hierarchy of accounts and add information to AccountsTree table

我现在正在努力完成第三步。那么,在将信息添加到Accounts表之后,如何找到填充AccountsTree表的层次结构呢?你知道吗

我期望的结果是:

ParentID    |   ChildID
1           |   2
2           |   3
3           |   4
3           |   4
3           |   5
3           |   6

有人经历过类似的挑战,能分享最有效的方法吗? 谢谢


Tags: andof信息iddb层次结构column帐户