数组关联Python

2024-05-31 23:26:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个模拟树形图的CSV文件,如下所示:

A,B #A is associated to B

A,C #A is associated to C

B,D #B is associated to D

B,E #B is associated to E

C,F #C is associated to F

C,G #C is associated to G

A是根(树的顶部)B&C是树枝,D、E、F、G是叶子(树枝的子部分)

我想知道有没有办法把它和它的关联放在一个数组中?你知道吗


Tags: 文件csvtois数组办法树枝associated
3条回答

假设文件my.csv包含您给出的示例输入,此代码将图形结构记录在两个简单的Python dict对象中:

parent = {}
children = {}
with open( 'my.csv', 'rt' ) as fh:
    for line in fh:
        # strip the comments and line endings
        if '#' in line: line = line[ :line.index( '#' ) ]
        line = line.strip()
        if line:
            # record the association
            node, subnode = line.split( ',', 1 )
            parent[ subnode ] = node
            children.setdefault( node, [] ).append( subnode )

语法children['A']允许您查找属于节点'A'的子节点列表,语法parent['B']允许您以另一种方式查找节点'B'的父节点。或者你也可以用以下方式打印整个内容:

for node, subnodes in sorted( children.items() ):
    print( '%r : %r' % ( node, subnodes ) )

输出:

'A' : ['B', 'C']
'B' : ['D', 'E']
'C' : ['F', 'G']

使用networkx生成有向图,matplotlib绘制有向图的图像:

import networkx as nx
import matplotlib.pyplot as plt

text =\
"""A,B
A,C
B,D
B,E
C,F
C,G"""

graph = nx.DiGraph()
for i in text.split('\n'):
    graph.add_edge(i[0], i[2])

nx.draw(graph, with_labels=True)
plt.show()

注意这一行:graph.add_edge(i[0], i[2]) 如果此图中不存在该节点,则会自动创建该节点。你知道吗

绘图: enter image description here

保存信息的一种自然结构是一个字典,其中每个条目的键是一个节点名(例如,C),它出现在csv文件中的一行左侧,而dict条目的值是一个数组,它最终包含作为该键直接子项的所有节点的名称(例如,[F,G])。你知道吗

因此,在处理csv文件的每一行(如B,D)时,请检查第一个元素(如B)是否已经是dict中的键。如果不是,请在dict中添加一个key=B和value=D的条目。如果已经存在,则将第二个元素附加到该键的数组值。例如,当您到达数据行B,E时,您将找到B的条目(B=>;[D]),并将E附加到其值上,得到[D,E]。你知道吗

完成后,如果某个节点的名称从未出现在任何条目的数组值中,则该节点就是树的根。如果有多个节点具有此属性,则这些节点中的每个节点都是树林中树的根。你知道吗

相关问题 更多 >