【问题标题】:building a tree from a csv file using python使用 python 从 csv 文件构建树
【发布时间】:2011-03-21 17:05:23
【问题描述】:

我的 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 中使用字典来实现这一点。这不会是决策树或二叉树等。

【问题讨论】:

  • 需要对数据进行哪些操作?你需要从一列到另一列的跳跃顺序吗?序列是多少行?
  • 如果您要进行的查找是相反的方向,为什么要以这种方式构建字典?为什么不简单地按照您想要查找的方式构建字典,即使用第一列作为键,第二列作为值?
  • 我很惊讶在 Python 中没有现成的解决方案,尤其是当您考虑到几乎所有在阳光下的东西都被捕获为该语言中方便的 3rd 方库时.

标签: python csv tree


【解决方案1】:

您可以使用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])

【讨论】:

    【解决方案2】:

    伪代码:

    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】:

      这是一个只使用字典的解决方案:

      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'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-08-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-22
        • 2019-08-04
        相关资源
        最近更新 更多