简体   繁体   English

如何在Python中从图中删除边

[英]How do I delete an edge from a graph in Python

I'm reading ThinkComplexity book, I'm new to python, so I have this code: 我正在阅读ThinkComplexity书,我是python的新手,所以我有以下代码:

class Graph(dict):
    def __init__(self, vs=[], es=[]):
        """
        :param vs: list of vertices/nodes in the graph
        :param es: list of edges/connection for the nodes
        :return: Object graph
        """

        for v in vs:
            self.add_vertex(v) #also node
        for e in es:
            self.add_edge(e) #arc/edge/line

     def add_vertex(self, v):
         """
         :param v: Add the node/vertex to the graph
         :return: Nothing just add
         """
         self[v] = {}

     def add_edge(self, e):
         """
         :param e: Add arc/edge/line to the graph here is in both directions as it is undirected graph, if there is a arc already replace it
         :return: Nothing just add
         """
         v, w = e
         self[v][w] = e
         self[w][v] = e

     def get_edge(self, v1, v2):
         try:
             if self != None:
                if self[v1][v2] == self[v2][v1]:
                     print 'got it'
                     return True

        except:
             return None


     def remove_edge(self, e, e2):
         try:
            if self != None:
                 del self[e][e2]
                 del self[e2][e]
                 print 'deleted\n', e[0], e[1]
                 return True

         except:
             return None


     def vertices(self): #get the list of nodes
         nodes = []
         for node in self.keys():
             nodes.append(node.label)
         print nodes, '\n'
         return nodes


    def edges(self):
         list_edges = []
         count = 0
         for node in self:
            for edges in self[node]:
                 count += 1
                 print self[node].values(), count
                 list_edges.append(self[node].values())

         return list_edges

    def out_vertices(self, v): #nodes connected to this node
        connected = []
        for node in v.keys():
            connected.append(node)
            print node, 'this node is connected to', v.keys()

        return connected

    def out_edges(self, v):
        list_out_edges = []
        for ed in v.values():
            print ed, 'edges from to'
            list_out_edges.append(ed)

        return list_out_edges



class Vertex(object): #nodes fro the graph
    def __init__(self, label=''):
        self.label = label

    def __repr__(self):
        return 'Vertex/Node(%s)' % repr(self.label)

    __str__= __repr__


class Edge(tuple):
     def __new__(cls, e1, e2):
        return tuple.__new__(cls, (e1, e2))

     def __repr__(self):
         return 'Edge(%s---%s) <-undirected' % (repr(self[0]), repr(self[1]))

     __str__ = __repr__

In chapter 2 4. Write a method named remove_edge that takes an edge and removes all references to it from the graph. 在第2章中4.编写一个名为remove_edge的方法,该方法采用一条边并从图形中删除对该边的所有引用。

I have the get_edge() code done, but t remove I don't know how to do it, any help?? 我已经完成了get_edge()代码,但是请删除我不知道该怎么做,有什么帮助吗? This would be an starting point to do a Bayes Network, so I want to learn about python and graphs. 这将是创建贝叶斯网络的起点,因此我想学习python和图形。 Thanks 谢谢

Like this: 像这样:

def remove_edge(g, e, e2):
   try:
       if g != None:
           del g[e][e2]
           del g[e2][e]
           print 'deleted\n', e[0], e[1]
       return True

   except:
       return None 

The keys in the dictionary can be objects, no only str. 字典中的键可以是对象,而不仅仅是str。 And need to do it both ways because is undirected 并且由于没有方向性,因此需要双向执行

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

相关问题 如何让用户删除 PyVis 网络图中的节点或边? - How do I let a user delete a node or edge in a PyVis network graph? 如何在使用python igraph创建的有向图中将权重添加到边缘标签中? - How do I add weights to edge labels in a directed graph created using python igraph? 如何为我的图表创建边列表? - How do i create an edge list in for my graph? 如何使用python字典保存图形边缘权重 - how Can I Use python dictionary to save graph edge weight 如何从边缘列表创建python-igraph图 - How to create a python-igraph Graph from edge list 如何从 Python 中的 CSV 文件制作图形/图表? - How do i make a graph/diagram from a CSV file in Python? 如何从 python 中的 highcharts 图中抓取数据? - How do I scrape data from a highcharts graph in python? 如何从python中的字典生成图形的邻接矩阵? - How do I generate an adjacency matrix of a graph from a dictionary in python? 如何从Python中的加权图计算路径的长度? - How do I calculate the length of a path from a weighted graph in Python? Python:如何从 OpenStreetMaps 导入水道作为图形,以便我可以使用 networkx 进行图形分析 - Python: How can I import waterways from OpenStreetMaps as a graph so I can do graph analysis with networkx
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM