这是一个将 networkx Graph 子类化并按照您的描述添加eq和hash函数的示例。我不确定它是否能解决您的问题,但应该是一个开始。
import networkx as nx
class myGraph(nx.Graph):
def __eq__(self, other):
return nx.is_isomorphic(self, other)
def __hash__(self):
return hash(tuple(sorted(self.degree().values())))
if __name__ == '__main__':
G1 = myGraph([(1,2)])
G2 = myGraph([(2,3)])
G3 = myGraph([(1,2),(2,3)])
print G1.__hash__(), G1.edges()
print G2.__hash__(), G2.edges()
print G3.__hash__(), G3.edges()
print G1 == G2
print G1 == G3
graphs = {}
graphs[G1] = 'G1'
graphs[G2] = 'G2'
graphs[G3] = 'G3'
print graphs.items()
输出类似:
3713081631935493181 [(1, 2)]
3713081631935493181 [(2, 3)]
2528504235175490287 [(1, 2), (2, 3)]
True
False
[(<__main__.myGraph object at 0xe47a90>, 'G2'), (<__main__.myGraph object at 0x1643250>, 'G3')]
[aric@hamerkop tmp]$ python gc.py
3713081631935493181 [(1, 2)]
3713081631935493181 [(2, 3)]
2528504235175490287 [(1, 2), (2, 3)]
True
False
[(<__main__.myGraph object at 0x1fefad0>, 'G2'), (<__main__.myGraph object at 0x27ea290>, 'G3')]