简体   繁体   中英

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

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]]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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