目前我的数据格式如下
A
A -> B -> C -> D -> Z
A -> B -> O
A -> X
这存储在列表[line1,line2等]
中现在我想以下列方式打印
A
|- X
|- B
|- O
|- C
|- D
|- Z
我是python的新手。我在想找' - >'在数组中的每个元素中并用空格替换。我不知道要往前走。
答案 0 :(得分:1)
这是一个让你入门的小代码(根据需要添加你自己的美化):
>>> def make_links(data):
'Create a dictionary mapping nodes to a set of their successors'
links = {}
for row in data:
nodes = row.replace(' ', '').split('->')
for a, b in zip(nodes[:-1], nodes[1:]):
links.setdefault(a, set()).add(b)
return links
>>> def draw_tree(links, start, depth=0):
'Recursively print a tree from a given starting point and given depth'
print(' ' * depth + start)
for node in sorted(links.get(start, [])):
draw_tree(links, node, depth+1)
>>> data = ['A', 'A -> B -> C -> D -> Z', 'A -> B -> O', 'A -> X']
>>> links = make_links(data)
>>> links
{'A': {'X', 'B'}, 'C': {'D'}, 'B': {'C', 'O'}, 'D': {'Z'}}
>>> draw_tree(links, start='A')
A
B
C
D
Z
O
X
答案 1 :(得分:1)
首先我们解析字符串:
data = """A
A -> B -> C -> D -> Z
A -> B -> O
A -> X
"""
lines = [x.split(' -> ') for x in data.split('\n') if x]
这将返回
[['A'], ['A', 'B', 'C', 'D', 'Z'], ['A', 'B', 'O'], ['A', 'X']]
然后我们建立它:
def addone(owner, data):
o = owner.setdefault(data.pop(0), {})
if data:
addone(o, data)
root = {}
for line in lines:
addone(root, line)
现在根将是:
{'A': {'X': {}, 'B': {'C': {'D': {'Z': {}}}, 'O': {}}}}
最后我们展示它:
def show(base, data):
while data:
k, v = data.pop(0)
print '%s|-%s' % (base, k)
if v:
if data:
show(base + '| ', v.items())
else:
show(base + ' ', v.items())
show("", root.items())
它将在我的地方输出如下:
|-A
|-X
|-B
|-C
| |-D
| |-Z
|-O
O和C有不同的顺序,因为python dict不记得顺序,这很容易通过排序或使用collections更改.OrderedDict