使用Python从CSV文件构建树
我的csv文件格式如下
Col1 Col2
a b
b c
c d
d e
x b
y c
z c
m x
h b
i b
我会创建一个字典来存储这些数据,像这样
{ b:[a,x,h,i] , c:[b,y,z], d:[c], e:[d], x:[m] }
从这个字典中,我想建立一个层级结构。比如说:当我遍历字典中的'a'时,我应该能够显示
a -> b -> c -> d -> e
同样,对于'y'也是如此
y -> c -> d -> e
我可以把这个想象成一个树形结构,想象成深度优先遍历,但我不太确定如何在python中用字典来实现这个。这个不是决策树或二叉树之类的。
3 个回答
0
这里有一个只使用字典的解决方案:
from itertools import chain
def walk(d, k):
print k,
while k in d:
k = d[k]
print '->', k,
data = {'b': ['a','x','h','i'], 'c': ['b','y','z'], 'd': ['c'], 'e': ['d'], 'x': ['m']}
hierarchy = dict(chain(*([(c, p) for c in l] for p, l in data.iteritems())))
# {'a':'b', 'c':'d', 'b':'c', 'd':'e', 'i':'b', 'h':'b', 'm':'x', 'y':'c', 'x':'b', 'z':'c'}
walk(hierarchy, 'a') # prints 'a -> b -> c -> d -> e'
walk(hierarchy, 'y') # prints 'y -> c -> d -> e'
0
伪代码:
filedict = {}
for row in file:
try:
filedict[row.col2].append(row.col1)
except:
filedict[row.col2] = [row.col1]
invdict = dict((v,k) for k, v in filedict.iteritems())
def parse(start):
if start not in invdict:
return []
next = invdict[start]
return [next] + parse(next)
3
你可以使用 Python-Graph 这个工具。
pairs = read_from_csv(...)
from pygraph.classes.digraph import digraph
gr = digraph()
gr.add_nodes(set([x for (x,y) in pairs]+[y for (x,y) in pairs]))
for pair in pairs:
gr.add_edge(pair)
#and now you can do something with the graph...
from pygraph.algorithms.searching import depth_first_search
print ' -> '.join(depth_first_search(gr, root='a')[1])
print ' -> '.join(depth_first_search(gr, root='y')[1])