[英]Trying to implement numbers from text file, into adjacency list project in python
我正在尝试从文本文件中获取数据并将其实现到下面的邻接代码中。
这是文本文件(test.txt):
1,1
1,1
4,1
4,5
5,1
5,3
1,1
3,3
使用此代码,我能够将文本文件分解为一个列表:
data = open("test.txt", "r")
list_of_lists = []
for line in data.readlines():
stripped_line = line.strip('\n')
line_list = list(map(int, stripped_line.split(',')))
list_of_lists.append(line_list)
data.close()print(list_of_lists)
adjLists = list_of_lists
return adjList
上面代码中的 output 是:[[1, 1], [1, 1], [4, 1], [4, 5], [5, 1], [5, 3], [1, 1] , [3, 3]]
我无法弄清楚的是如何从列表中获取数据,并将其实现到下面的代码中,以便将其创建到运行文本文件编号的邻接列表中。
def __init__(self, nodes : int) :
# Store the adjacency list as a dictionary
# { 0 : [ 1, 2 ], 1 : [ 3, 4 ] }
# The default dictionary would create an empty list as a default (value)
# for the nonexistent keys.
self.adjlist = defaultdict(list)
self.nodes = nodes
def AddEdge (self, src : int, dst : int) :
self.adjlist[src].append(dst)
self.adjlist[dst].append(src)
def Display_AdjList(self) :
for item in self.adjlist.items() :
print (item)
def main():
nodes = 7
g = Graph(nodes)
g.AddEdge(0, 1)
g.AddEdge(0, 2)
g.AddEdge(1, 3)
g.AddEdge(1, 4)
g.AddEdge(2, 3)
g.AddEdge(3, 5)
g.AddEdge(4, 6)
g.AddEdge(5, 6)
print("Adjacency list for storing graph")
g.Display_AdjList()
if __name__ == "__main__" :
main()
列表中两个项目的每个列表都是邻接矩阵中的一个边。 您需要创建一个图,然后遍历每条边并将它们添加到图中:
g = Graph(nodes)
for edge in adjList:
g.AddEdge(*edge)
g.Display_AdjList()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.