面向对象的, 可以再封装
raw = \
(
{
'id': 1,
'name': 'My Documents',
'pid': 0
},
{
'id': 2,
'name': 'photos ',
'pid': 1
},
{
'id': 3,
'name': 'Friend',
'pid': 2
},
{
'id': 4,
'name': 'Wife',
'pid': 2
},
{
'id': 5,
'name': 'Company',
'pid': 2
},
{
'id': 6,
'name': 'Program Files',
'pid': 1
},
{
'id': 8 ,
'name': 'Java ',
'pid': 6
},
)
class Node:
def __init__(self, id, name, pid):
self.id = id
self.name = name
self.pid = pid
self.children = []
self.parent = None
def __lt__(self, other):
if self.pid < other.pid:
return True
elif self.pid == other.pid and self.id < other.id:
return True
return False
@staticmethod
def print_path(n):
path = n.name
while n.parent:
path = n.parent.name + '_' + path
n = n.parent
print(path)
nodes = [Node(**_) for _ in raw]
nodes.sort()
tmp = {}
for node in nodes:
tmp[node.id] = node
if node.pid in tmp:
tmp[node.pid].children.append(node)
node.parent = tmp[node.pid]
for node in nodes:
Node.print_path(node)
'''
My Documents
My Documents_photos
My Documents_Program Files
My Documents_photos _Friend
My Documents_photos _Wife
My Documents_photos _Company
My Documents_Program Files_Java
'''