簡體   English   中英

嘗試將文本文件中的數字實現到 python 中的鄰接列表項目中

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM