Skip to content

Commit 35fb367

Browse files
committed
新增python树的操作
1 parent 49dec35 commit 35fb367

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

test/tree.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#!/usr/bin/env python
2+
# encoding: utf-8
3+
4+
"""
5+
@author: zhanghe
6+
@software: PyCharm
7+
@file: tree.py
8+
@time: 2017/5/22 下午6:57
9+
"""
10+
11+
12+
import json
13+
from collections import defaultdict
14+
15+
16+
def tree():
17+
"""
18+
定义一棵树
19+
python 字典的特性,赋值操作必须事先声明,所以这里使用 collections 很方便的为字典设置初始值
20+
:return:
21+
"""
22+
return defaultdict(tree)
23+
24+
25+
if __name__ == '__main__':
26+
users = tree()
27+
users['jack_1']['jack_2_1']['jack_3_1'] = {}
28+
users['jack_1']['jack_2_1']['jack_3_2'] = {}
29+
users['jack_1']['jack_2_2'] = {}
30+
users['jack_1']['jack_2_2']['jack_3_1'] = {}
31+
32+
users['lily_1']['lily_2_1']['lily_3_1'] = {}
33+
users['lily_1']['lily_2_2']['lily_3_2'] = {}
34+
users['lily_1']['lily_2_3']['lily_3_3'] = {}
35+
36+
users['emma_1']['emma_2_1'] = {}
37+
38+
# 打印 users 原始结构
39+
print users
40+
41+
# 打印 users json 结构
42+
print(json.dumps(users, indent=4))
43+
44+
# 第一层(users的key)
45+
print [i for i in users]
46+
47+
# 第二层(users子节点的key)
48+
print [i for i in users['jack_1']]
49+
50+
# 第三层(users孙节点的key)
51+
print [i for i in users['jack_1']['jack_2_1']]

0 commit comments

Comments
 (0)