简体   繁体   English

尝试将文本文件中的数字实现到 python 中的邻接列表项目中

[英]Trying to implement numbers from text file, into adjacency list project in python

I am trying to take data from a text file and implement it into this adjacency code below.我正在尝试从文本文件中获取数据并将其实现到下面的邻接代码中。

This is the text file (test.txt):这是文本文件(test.txt):

1,1
1,1
4,1
4,5
5,1
5,3
1,1
3,3

Using this code I was able to break down the text file int a list:使用此代码,我能够将文本文件分解为一个列表:

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

The output from the code above is: [[1, 1], [1, 1], [4, 1], [4, 5], [5, 1], [5, 3], [1, 1], [3, 3]]上面代码中的 output 是:[[1, 1], [1, 1], [4, 1], [4, 5], [5, 1], [5, 3], [1, 1] , [3, 3]]

What I cannot figure out, is how to take the data from the list, and implement it into the code below so it creates it into an adjacency list it runs the text file numbers.我无法弄清楚的是如何从列表中获取数据,并将其实现到下面的代码中,以便将其创建到运行文本文件编号的邻接列表中。

    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()

Each list of two items in your list is one edge in the adjacency matrix.列表中两个项目的每个列表都是邻接矩阵中的一个边。 You need to create a graph, then loop through each of the edges and add them to the graph:您需要创建一个图,然后遍历每条边并将它们添加到图中:

g = Graph(nodes)
for edge in adjList:
    g.AddEdge(*edge)
g.Display_AdjList()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM