python获取id标签对应数据_python pid/id 分组得到如何得到制定格式的数据?

面向对象的, 可以再封装

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

'''

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值