[英]Creating an adjacency list with dictionaries
The question asks: A graph can be represented in a file by listing one link per line, with each link represented by a pair of nodes.问题是:可以通过在文件中每行列出一个链接来表示图,每个链接由一对节点表示。 Write a function that reads such a file and returns an adjacency list (as a dictionary) for the graph.
编写一个函数来读取这样的文件并返回图形的邻接列表(作为字典)。 Notice that, for each line AB in the file, your function will need to insert node B into the list of neighbors A and insert node A into the list of neighbors of B .
请注意,对于文件中的每一行AB ,您的函数需要将节点B插入到邻居A的列表中,并将节点A插入到B的邻居列表中。 Example of a possible file:
可能的文件示例:
graph.txt
A B
A C
A D
B E
C D
C E
I expect the final list to look something like this:我希望最终的列表看起来像这样:
adjList = {
A: [B, C, D],
B: [A, E],
C: [A, D, E],
D: [A, C],
E: [B, C],
}
You can use defaultdict to answer this question.您可以使用 defaultdict 来回答这个问题。 I wrote the code and it is working but you may like to think about it first.
我编写了代码并且它正在运行,但您可能想先考虑一下。
dictAdjacency=defaultdict(list)
with open('C:/graph.txt') as readObj:
lines=readObj.readlines()
for line in lines:
tempList=line.rstrip('\n').split(' ')
dictAdjacency[tempList[0]].append(tempList[1])
dictAdjacency[tempList[1]].append(tempList[0])
print(dictAdjacency)
defaultdict(<class 'list'>,
{
'A': ['B', 'C', 'D'],
'B': ['A', 'E'],
'C': ['A', 'D', 'E'],
'D': ['A', 'C'],
'E': ['B', 'C']
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.