这就是我将如何做到的。由于树只有两层深——不管你想要的输出格式似乎暗示了什么——没有必要使用递归来遍历它的内容,因为迭代工作得很好。可能这与您引用的#f 代码完全不同,因为我不懂该语言,但它更短且更具可读性——至少对我而言。
from itertools import izip
def print_tree(tree):
for key in sorted(tree.iterkeys()):
data = tree[key]
previous = data[0], data[1], data[2]
first = True
for name, activity, value in izip(*[iter(data)]*3): # groups of three
activity = activity if first or activity != previous[1] else ' '*len(activity)
print '{} ->'.format(key) if first else ' ',
print '{} -> {} -> {}'.format(activity, name, value)
previous = name, activity, value
first = False
d = {'a': ['Adam', 'Book', 4],
'b': ['Bill', 'TV', 6, 'Jill', 'Sports', 1, 'Bill', 'Computer', 5],
'c': ['Bill', 'Sports', 3],
'd': ['Quin', 'Computer', 3, 'Adam', 'Computer', 3],
'e': ['Quin', 'TV', 2, 'Quin', 'Book', 5],
'f': ['Adam', 'Computer', 7]}
print_tree(d)
输出:
a -> Book -> Adam -> 4
b -> TV -> Bill -> 6
Sports -> Jill -> 1
Computer -> Bill -> 5
c -> Sports -> Bill -> 3
d -> Computer -> Quin -> 3
-> Adam -> 3
e -> TV -> Quin -> 2
Book -> Quin -> 5
f -> Computer -> Adam -> 7
更新
要按名称而不是活动组织输出,您需要更改三行,如下所示:
from itertools import izip
def print_tree(tree):
for key in sorted(tree.iterkeys()):
data = tree[key]
previous = data[0], data[1], data[2]
first = True
for name, activity, value in sorted(izip(*[iter(data)]*3)): # changed
name = name if first or name != previous[0] else ' '*len(name) # changed
print '{} ->'.format(key) if first else ' ',
print '{} -> {} -> {}'.format(name, activity, value) # changed
previous = name, activity, value
first = False
修改后的输出:
a -> Adam -> Book -> 4
b -> Bill -> Computer -> 5
-> TV -> 6
Jill -> Sports -> 1
c -> Bill -> Sports -> 3
d -> Adam -> Computer -> 3
Quin -> Computer -> 3
e -> Quin -> Book -> 5
-> TV -> 2
f -> Adam -> Computer -> 7