Python 评论树

1.递归的方式的实现:效率低,父评论一定要在子评论前面

import collections

aaa = collections.OrderedDict()
aaa['k1']='v1'
aaa['k2']='v2'
aaa['k3']='v3'

print(aaa)  # OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])

for k,v in aaa.items():
    print(k,v)  # k1 v1  | k2 v2 |  k3 v3
collections.OrderedDict()
#!/usr/bin/env python
# --*-- encoding:utf-8 --*--
import collections
# 元组第三个值为空,则是评论文章的评论
comment_list = [
    (1,'aaa',None),
    (2,'bbb',None),
    (3,'aaa-aaa',1),
    (4,'bbb-bbb',2),
    (5,'aaa-aaa-aaa',3),
    (6,'bbb-bbb-bbb',4),
    (7,'ccc',None),
    (8,'ddd',None),
    (9,'ccc-ccc',7)
]

def build_tree(comment_list):
    #[(),(),()]  OrderedDict([('k1', 'v1'), ('k2', 'v2'), ('k3', 'v3')])
    comment_dict = collections.OrderedDict()
    for comment_obj in comment_list:
        if comment_obj[2] is None:
            comment_dict[comment_obj]=collections.OrderedDict()
        else:
            search_tree(comment_dict,comment_obj)
    return comment_dict

#递归搜索
def search_tree(comment_dict,comment_obj):
    for k,v in comment_dict.items():
        if comment_obj[2]==k[0]:
                comment_dict[k][comment_obj]=collections.OrderedDict()
                return
        else:
            search_tree(comment_dict[k],comment_obj)

if __name__ == '__main__':
    print(build_tree(comment_list))
    #OrderedDict(
    # [((1, 'aaa', None), OrderedDict([((3, 'aaa-aaa', 1), OrderedDict([((5, 'aaa-aaa-aaa', 3), OrderedDict())]))])),
    #  ((2, 'bbb', None), OrderedDict([((4, 'bbb-bbb', 2), OrderedDict([((6, 'bbb-bbb-bbb', 4), OrderedDict())]))])), 
    # ((7, 'ccc', None), OrderedDict([((9, 'ccc-ccc', 7), OrderedDict())])),
    #  ((8, 'ddd', None), OrderedDict())])
实现代码

2.高效实现

#!/usr/bin/env python
# --*-- encoding:utf-8 --*--

test_dict = {'k1':'v1','k2':'v2'}
temp = test_dict.get('k1')
print(temp)   # v1
temp = 'vv'
print(test_dict)  #{'k2': 'v2', 'k1': 'v1'}


test_dict = {1:{'k1':'v1'},2:{'k2':'v2'}}
temp = test_dict.get(1)
print(temp) #
temp.update(k3='v3')
print(test_dict)  # {1: {'k1': 'v1', 'k3': 'v3'}, 2: {'k2': 'v2'}}
知识补充
  1. python中的字典和列表都是引用数据类型,里面就是指针指向的内存地址,当修改实际的内存中的值时,所有指向该地址的指针对应的值都被改变。
  2. python中的dict数据类型是键值对的形式,内部实现是通过hash实现的,所以通过key获取值的速度比列表获取值的速度快很多。

 注:dict,list,set 都是引用类型

#!/usr/bin/env python
# --*-- encoding:utf-8 --*--

# comment_list = [
#     (1,'aaa',None),
#     (2,'bbb',None),
#     (3,'aaa-aaa',1),
#     (4,'bbb-bbb',2),
#     (5,'aaa-aaa-aaa',3),
#     (6,'bbb-bbb-bbb',4),
#     (7,'ccc',None),
#     (8,'ddd',None),
#     (9,'ccc-ccc',7)
# ]

comment_list=[
    {'id':1,'comment':'aaa','pid':0},
    {'id':2, 'comment': 'bbb', 'pid': 0},
    {'id':3, 'comment': 'aaa-aaa', 'pid': 1},
    {'id':4, 'comment': 'bbb-bbb', 'pid': 2},
    {'id':5, 'comment': 'aaa-aaa-aaa', 'pid': 3},
    {'id':6, 'comment': 'bbb-bbb-bbb', 'pid': 4},
    {'id':7, 'comment': 'ccc', 'pid': 0},
    {'id':8, 'comment': 'ddd', 'pid': 0},
    {'id':9, 'comment': 'ccc-ccc', 'pid': 7}
]
#结果树
comment_res = []
#临时字典
temp_dict = {}
#循环评论列表
for item in comment_list:
    # 为评论的每一项添加 [{'id': 1, 'comment': 'aaa', 'child': [], 'pid': 0}, {'id': 2, 'comment': 'bbb', 'child': [], 'pid': 0}]
    item.update({'child': []})
    # {1:{'id':1,'comment':'aaa','pid':0},2:{'id':2, 'comment': 'bbb', 'pid': 0},}
    temp_dict[item['id']]= item

#循环评论列表
for item in comment_list:
    # 拿到当前行对应的父亲的地址 ,并不是父亲的值  {'id': 3, 'comment': 'aaa-aaa', 'child': [], 'pid': 1}
    p_row = temp_dict.get(item['pid'])
    if p_row is None:
        # 没有父亲的就为空 ,结果树中添加根节点
        comment_res.append(item)
    else:
        # 有父亲的,根据父亲的地址 加入子评论
        p_row['child'].append(item)

print(comment_res)
实现代码

 

posted @ 2017-06-13 23:18  1916  阅读(158)  评论(0)    收藏  举报