擅长:python、mysql、java
<p>为此,您可以先构建数据节点树,然后遍历所有分支以构建路径列表:</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
"""
data = [ line.split(",") for line in text.split("\n") if line.strip() ]
keys = { k:name for k,name,*_ in data } # to get names from keys
tree = { k:{} for k in keys } # initial tree structure with all keys
root = tree[""] = dict() # tree root
for k,_,_,parent in data:
tree[parent].update({k:tree[k]}) # connect children to their parent
nodes = [[k] for k in root] # cumulative paths of keys
paths = [] # list of paths by name
while nodes:
kPath = nodes.pop(0)
subs = tree[kPath[-1]] # get children
if subs: nodes.extend(kPath+[k] for k in subs) # accumulate nodes
else : paths.append([keys[k] for k in kPath]) # return path if leaf node
</code></pre>
<p>输出:</p>
<pre><code>print(paths)
[['Product1'], ['Product3'], ['Product7', 'Product4'], ['Product7', 'Product2', 'Product5']]
</code></pre>