回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我正在尝试创建一个包含树中所有可能路径的列表。我给出了以下结构(DB的子集):</p>
<pre><code>text = """
1,Product1,INVOICE_FEE,
3,Product3,INVOICE_FEE,
7,Product7,DEFAULT,
2,Product2,DEFAULT,7
4,Product4,DEFAULT,7
5,Product5,DEFAULT,2
"""
</code></pre>
<p>其中列为:ID、产品名称、发票类型、引用到父级ID。
我想创建包含所有可能路径的列表,如示例中所示:</p>
<pre><code>[[Product1],[Product3],[Product7,Product2,Product5],[Product7,Product4]]
</code></pre>
<p>我谨此陈辞:</p>
<pre><code>lines = [ l.strip() for l in text.strip().splitlines() ]
hierarchy = [ tuple(l.split(',')) for l in lines ]
parents = defaultdict(list)
for p in hierarchy:
parents[p[3]].append(p)
</code></pre>
<p>为了创建树,我想找到所有路径:</p>
<pre><code>def pathsMet(parents, node=''):
childNodes = parents.get(node)
if not childNodes:
return []
paths = []
for ID, productName, invoiceType, parentID in childNodes:
paths.append([productName] + pathsMet(parents, ID))
return paths
print(pathsMet(parents))
</code></pre>
<p>我得到的结果如下:</p>
<pre><code>[['FeeCashFlow1'], ['FeeCashFlow3'], ['PrincipalCashFlow7', ['AmortisationCashFlow3', ['AmortisationCashFlow2']], ['AmortisationCashFlow4']]]
</code></pre>
<p>如何更正代码以获得以下输出:</p>
<pre><code>[['FeeCashFlow1'], ['FeeCashFlow3'], ['PrincipalCashFlow7', 'AmortisationCashFlow3', 'AmortisationCashFlow2'], ['PrincipalCashFlow7','AmortisationCashFlow4']]
</code></pre>