Python file reading generates a right directed graph

Use the form of nested dictionaries to generate a directed directed graph, and read the data in the txt file. The format of the given txt file is as follows, separated by spaces. Generated examples are as follows:

{1: {2: 2, 3: 6}, 3: {4: 7}, 2: {4: 3}}

 The specific implementation code is as follows

class Graph_all_paths():
    def __init__(self):
      self.file_path = 'x.txt'  # 图文件
      self.total_eage#总边数
      self.graph = {}#用来存储图
    

    def initial_graph(self, file_path):
        f = open(file_path)
        lines = [l.split() for l in f.readlines() if l.strip()]
        # print(lines)
        self.total_eage = len(lines)  # 原始图的总线路
        for i in lines:
            if eval(i[0]) not in self.graph.keys():
                self.graph[eval(i[0])] = {eval(i[1]): eval(i[2])}
            else:
                self.graph[eval(i[0])][eval(i[1])] = eval(i[2])
        return self.graph#返回的图即为所求

I believe you should be able to use classes~

Guess you like

Origin blog.csdn.net/weixin_63676550/article/details/130179357